樣品表
create table t123 (Id int, Name varchar(10), [Order] int, Value int)
insert t123 select
1,'a','1',100 union all select
2,'b','2',200 union all select
3,'c','1',300 union all select
4,'d','1',100 union all select
5,'e','2',300
查詢的SQL Server 2005及以上
select a.[order], STUFF((
select ','+b.name
from t123 b
where b.[order] = a.[order]
order by b.name
for xml path('a'), type).value('.','nvarchar(max)'),1,1,'') Name,
SUM(a.value) value,
COUNT(*) [count]
from t123 a
group by a.[order]
輸出
order Name value count
----------- ------------ ----------- -----------
1 a,c,d 500 3
2 b,e 500 2
u能請解釋一下到底是怎麼回事呢..我的表是不是一個真正的表,它從多個表的連接的結果集。 – Sarah 2011-04-06 23:13:25