我有一个名为terms的表,我使用的是sql server 2014
termID termname
1 term1
2 term2
3 term3
4 term4
我想要这样的结果
termID termname
1 term1
2 term1 and term2
3 term1 and term2 and term3
4 term1 and term2 and term3 and term4
我是用 LAG()
,但我只能得到前一个值。我需要得到前面所有列的值。
select termid, CASE WHEN ISNULL(prev_word,'')<>'' THEN prev_word+' and '+ termname ELSE termname END
from (
select termID,
lag(termname) over (order by termID) as prev_word,
termname
from terms
) as t
1条答案
按热度按时间mkh04yzy1#
一些数据库(如postgres)支持
string_agg()
作为一个窗口函数,您可以将其编写为:... 不幸的是,SQLServer还不支持这种语法。
另一种方法是递归查询。我不会这么想
termid
总是从1
并且总是不带间隙地递增,因此首先用row_number()
,然后迭代遍历数据集,一步一步累积字符串:如果列表中的值超过100个,则需要添加
option (maxrecursion 0)
在查询的最后(否则将达到100次迭代的默认限制)。db小提琴演示: