當前位置:首頁 » 編程語言 » sql多行轉多列

sql多行轉多列

發布時間: 2024-11-02 19:17:52

『壹』 sql中一對多關系的查詢結果的多行轉換成一行多列

--用動態sql實現行轉列。因用到了row_number,只適用於sqlserver2005及以上版本
--測試數據
with
[user](ID,name,roleid)
as(
select1,'bobo','r1'unionall
select2,'coco','r1'unionall
select3,'dodo','r1'unionall
select4,'eoeo','r2'unionall
select5,'fofo','r2'),
[role](ID,name)
as(
select'r1','admin'unionall
select'r2','user')
--兩表聯合查詢後暫存入臨時表
selectb.IDroleid,b.namerolename,a.nameusername,row_number()over(partitionbyb.IDorderbya.ID)seq
into#t
from[user]a
innerjoin[role]bona.roleid=b.ID;
--拼接動態sql
declare@sqlvarchar(max);
set@sql='';
select@sql=@sql+
',max(caseseqwhen'+cast(tt.seqasvarchar)+'thenusernameelse''''end)user'+cast(tt.seqasvarchar)
from(selectdistinctseqfrom#t)tt
orderbyseq;
set@sql='selectrolename'+@sql+'from#tgroupbyroleid,rolename';
--列印動態sql
select@sql;
--執行動態sql
exec(@sql);
--刪除臨時表
droptable#t;

生成的動態sql為:

selectrolename,
max(caseseqwhen1thenusernameelse''end)user1,
max(caseseqwhen2thenusernameelse''end)user2,
max(caseseqwhen3thenusernameelse''end)user3
from#tgroupbyroleid,rolename

最終查詢結果為:

『貳』 sql多行多列合並成一行多列,

您好利用分析函數 sum max min 等均可實現此功能(oracle 中 空值不參與大小比較(11g是這樣的 其他版本需要你自己測試相愛))
如:
select 產品, max(標價),max(二標價),max(三標價) from table group by 產品;
或者
select 產品, sum(標價)),sum(二標價),sum(三標價) from table group by 產品;

熱點內容
上傳mp3外鏈 發布:2025-03-17 22:11:06 瀏覽:798
c語言寫音樂 發布:2025-03-17 22:10:55 瀏覽:914
c語言位或和或 發布:2025-03-17 21:53:56 瀏覽:915
淘寶圖片上傳格式 發布:2025-03-17 21:48:55 瀏覽:941
博雅幹細胞存儲 發布:2025-03-17 21:24:07 瀏覽:53
dota2卡爾腳本 發布:2025-03-17 21:11:27 瀏覽:71
應用市場網站源碼 發布:2025-03-17 21:09:46 瀏覽:413
linux怎麼掛載 發布:2025-03-17 21:08:23 瀏覽:897
疫情資料庫 發布:2025-03-17 20:58:00 瀏覽:670
excel怎麼破解密碼 發布:2025-03-17 20:49:32 瀏覽:360