Create Function function(@ID Int, @i Int)
Returns VarChar(8000)
As
Begin
-- variables for storing data and return values
Declare @string VarChar(8000), @temp VarChar(8000)
Select @i = @i-1, @string = Field1 + ', ' From dbo.Errors E1 Where Id = @ID And
@i = (Select Count(*) From dbo.Errors E2 Where E2.Id = E1.Id and E2.Field1 <= E1.Field1);
If @i > 0
Begin
Exec @temp = dbo.function@ID, @i;
-- concatenate values every time the funtion returns
Set @string = @temp + @string
End
-- return the resulatant data;
Return @r;
End
Go
您的函数需要通过以下方式调用:
Select ID, dbo.function(ID, Count(Field1)) From dbo.Errors Group By ID;
SELECT ID ,(Select SUBSTRING(
(SELECT ',' + FIELD1 AS 'data()'
FROM TABLE WHERE ID = table.ID
FOR XML PATH('')
), 2 , 9999)) As FIELD1
FROM table
GROUP BY ID
with s as --this is your data
(select stack(5,
1,'a',1,
1,'b',3,
1,'c',2,
2,'d',1,
2,'e',2) as (id,field1,seq_number)
)
select s.id, concat_ws('',collect_list(s.field1)) as field1
from
(select s.id, s.field1, s.seq_number from s sort by s.seq_number) s --SORT is here
group by s.id;
3条答案
按热度按时间ggazkfy81#
您可以使用递归函数来获得所需的结果。但请记住,如果数据的维数很高,请尝试另一种方法,因为在某些语言(即sql server)中,递归函数的嵌套级别不超过32!
您的函数需要通过以下方式调用:
希望这对你有帮助!
bgibtngc2#
看这里
goqiplq23#
使用
collect_list
将字符串聚合为数组和concat_ws
连接数组。collect_list
正在使用ArrayList
,它按插入的顺序保存数据。使用sort
在前面的子查询中collect_list
对数组中插入的值进行排序。Hive中的测试:
结果: