[英]Deriving columns from other column in T-SQL
我在T-SQL的书中有一张表,到目前为止只有一列,其中有一堆书名:
Book Title
------------------
Romeo and Juliet
Hamlet
All The King's Men
我想做的是添加第二列,称为“其他标题”,其中包含该列中除当前行标题以外的所有其他标题的字符串,即
Book Title Other Titles
------------------ ----------------
Romeo and Juliet Hamlet, All The Kings Men
Hamlet R & J, All The King's Men
All The King's Men R&J, Hamlet
我知道我可能必须在T-SQL中使用STRING_AGG,但是我似乎无法弄清楚。 有任何想法吗?
如果您的sql-server版本支持STRING_AGG
函数。
您可以尝试根据条件t2.[Book Title] <> t1.[Book Title]
进行自我加入t2.[Book Title] <> t1.[Book Title]
然后使用STRING_AGG
函数,
CREATE TABLE T(
[Book Title] VARCHAR(50)
);
INSERT INTO T VALUES ('Romeo and Juliet');
INSERT INTO T VALUES ('Hamlet');
INSERT INTO T VALUES ('All The King''s Men');
SELECT t1.[Book Title],
STRING_AGG ( t2.[Book Title] , ',' ) 'Other Titles'
FROM T t1
INNER JOIN T t2 ON t2.[Book Title] <> t1.[Book Title]
group by t1.[Book Title]
我将使用相关的子查询来做到这一点:
select b.*,
(select string_agg(b2.title, ', ') within group (order by b2.title)
from books b2
where b2.title <> b.title
) as other_titles
from books b;
相关子查询使您可以更轻松地保留表中可能包含的其他列。
不过,老实说,性能不会特别好。 您可以考虑将所有内容汇总在一起,然后删除标题:
select b.*,
stuff(replace(bb.titles, ', ' + b.title, ''), 1, 2, '') as other_titles
from books b cross join
(select ', ' + string_agg(b2.title, ', ') as titles
from books
) bb;
与在整个表中循环以为每一行重建字符串相比,在titles
上调用replace()
通常具有更好的性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.