我有一种情况,我需要将 DENSE_RANK 函数的 SQL 结果“连接”成一个字符串,我不知道有另一个 SQL 函数可以做到这一点。
问题是我最终从 DENSE_RANK 函数中获得了相同等级的多行,这是可以预料的,例如:
ID Info Total Rank
1 A 2 1
1 B 2 1
1 C 1 2
2 D 2 1
2 E 1 2
3 F 1 1
我想要实现的是如下所示的结果,所以因为 ID 1 有 2 个信息具有相同的等级,所以我想将它们“连接”成一个字符串(逗号分隔):
ID Info1 Info2
1 A,B C
2 D E
3 F G
我目前有以下代码,它为我提供了 DENSE_RANK 的结果,但我一直在试图弄清楚如何在我有一个“连接”字符串的地方获得我的最终结果集,我尝试了一些不同的技术并且有通过stackoverflow好好看看,但我找不到一种让它工作的方法。
SELECT t1.ID
,t2.Info1
,t3.Info2
,t4.Info3
FROM table1 t1 WITH (NOLOCK)
LEFT JOIN (SELECT t2.ID
,t2.Info AS Info1
,t2.Total
FROM (SELECT t2.ID
,t2.Info
,t2.Total
,DENSE_RANK() OVER (PARTITION BY t2.ID ORDER BY t2.Total DESC) AS DENSE_RANK
FROM table2 t2 WITH (NOLOCK)) t2
WHERE DENSE_RANK = 1) AS t2 ON t1.ID = t2.ID
LEFT JOIN (SELECT t3.ID
,t3.Info AS Info2
,t3.Total
FROM (SELECT t3.ID
,t3.Info
,t3.Total
,DENSE_RANK() OVER (PARTITION BY t3.ID ORDER BY t3.Total DESC) AS DENSE_RANK
FROM table3 t3 WITH (NOLOCK)) t3
WHERE DENSE_RANK = 2) AS t3 ON t1.ID = t3.ID
LEFT JOIN (SELECT t4.ID
,t4.Info AS Info3
,t4.Total
FROM (SELECT t4.ID
,t4.Info
,t4.Total
,DENSE_RANK() OVER (PARTITION BY t4.ID ORDER BY t4.Total DESC) AS DENSE_RANK
FROM table4 t4 WITH (NOLOCK)) t4
WHERE DENSE_RANK = 3) AS t4 ON t1.ID = t4.ID
ORDER BY t1.ID ASC