Sql server TSQL如何动态构建字符串?

Sql server TSQL如何动态构建字符串?,sql-server,tsql,Sql Server,Tsql,假设我有一个列如下的表: | Name | Cat_id | 我不记得可以构建这样一个varchar的函数 1,24|4,56|5,67 其中,逗号前的数字是Cat_id,逗号后的数字是该id的行数。有什么想法吗?这可以做到: declare @s varchar(8000) set @s = '' select @s = @s + cast(cat_id as varchar(20)) + ',' + cast(count(*) as varchar(20)) + '|' fr

假设我有一个列如下的表:

| Name | Cat_id |
我不记得可以构建这样一个varchar的函数

1,24|4,56|5,67

其中,逗号前的数字是Cat_id,逗号后的数字是该id的行数。有什么想法吗?

这可以做到:

declare @s varchar(8000)
set     @s = ''

select  @s = @s + cast(cat_id as varchar(20)) + ',' + cast(count(*) as varchar(20)) + '|'
from    SomeTable
group by cat_id
option(maxdop 1) -- this sure there are no funny side-effects because of parallelism

print @s
或者,您可以使用“for xml”或游标,但这应该更快


关于GJ

希望这将有助于SQL server 2005+。。。我没有测试该程序,因为我目前没有SQL Server

With Cte1 As(
Select Cat_ID, Count(Cat_ID),Cast(Cat_ID as Varchar) + Cast(Count(Cat_ID)) as MergedColumn from tbl 
group by Cat_ID),
cte2 as(
Select 
    Cat_ID
    , mergedData  = stuff((Select cast(MergedColumn + '|' as varchar) from tbl t2 where t2.Cat_ID  = t1.Cat_ID 
                  for xml path('')),1,1,'')
from tbl t1)

select mergedData from Cte2

重复:管道符号是输出的一部分吗?输出是否只有一行,带有管道分隔值cat_id、countcat_id,或者您希望每个cat_id有一行?嗯,计数始终返回1,即使我从cat_id=st.cat_id的某个表创建子查询select count,而不是该计数*应该可以工作。。。确定你没有唯一的id吗?不太可能…废话,对不起,看错了。将其设为@S=@S+name+,'。。等按名称分组。我们是根据猫的id而不是名字分组的。编辑:不,你确实要求按猫的id分组。你确定吗?