2013年5月21日 星期二

MSSQL查詢資料Row(s) to String

Words: row to one line, rows to string

已存在資料如下:
代碼表(code table):
code name
A apple
B banana
L lemon


資料列(data):
id name fruit_code quota rest
1 Alice A 50 12
2 Alice B 40 9
3 Bob L 30 22
4 Bob A 30 8

預期查詢結果如下輸出:

查詢結果(result):

name Total Rest Detail
Alice 69 A-apple(38),B-banana(31)
Bob 30 L-lemon(8),A-apple(22)

SQL語法:
select 
  name
  , sum(quota)-sum(rest) 'Total Rest'
  ,STUFF(
     (select 
           ','
          +cast(fruit_code as varchar)
          +'-'
          +(select name from fruit_code t3 where t3.code=t1.fruit_code)
          +'('+cast(quota-rest as varchar)+')'
      from usage t1 
      where t1.name=t2.name 
      for xml path(''))
     ,1
     ,1
     ,''
  ) Detail
from usage t2
group by name




沒有留言: