表結構:
姓名 科目 成績
張三 語文 89
張三 數學 73
李四 語文 73
李四 數學 73
需要的格式:
姓名 科目成績
張三 語文=89,數字=73
李四 語文=73,數字=73
查詢語句:
select 姓名,wm_concat(to_char(科目||'='||成績)) from 表名 where 姓名 in ('張三','李四')
* 註:wm_concat 內必須要文本字元
但在sql server裡沒有這個函數,那怎麼辦。只能另找其他方法了。
select 姓名, [科目]=stuff((select ','+[科目] from 表名 A t where A.姓名=B.姓名 for xml path('')), 1, 1, '') from 表名 B group by 姓名
排序語句:
select 姓名,wm_concat(to_char(科目||'='||成績)) over (order by 科目 rows between unbounded preceding and unbounded following) 成績 from 表名 where 姓名 in ('張三','李四') where rownum=1
* 註:
分組欄位 為相同的行值
*over(開窗函數)的使用說明
over(order by 欄位) 照欄位排序over(partition by 欄位)按照欄位分區範例:over(order by 欄位 rows between 2 preceding and 4 following)每行對應的資料視窗是之前2行,之後4行over(order by 欄位 rows between unbounded preceding and unbounded following)每行對應的資料視窗是從第一行到最後一行over(partition by null) 等級從第一行到最後一行
參考:http://zonghl8006.blog.163.com/blog/static/4528311520083995931317/