且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL查询以逗号分隔符以及SQL Server中的按列获取聚合结果

更新时间:2022-11-27 15:33:41

您要使用 FOR XML PATH 构造:

select 
    ID, 
    stuff((select ', ' + Value 
           from YourTable t2 where t1.ID = t2.ID 
           for xml path('')),
          1,2,'') [Values]
from YourTable t1
group by ID

STUFF 函数是为了摆脱前导','

The STUFF function is to get rid of the leading ', '.

您还可以看到另一个此处的示例:

You can also see another examples here:

  • SQL same unit between two tables needs order numbers in 1 cell
  • SQL and Coldfusion left join tables getting duplicate results as a list in one column