當前位置:首頁 » 編程語言 » 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 產品;

熱點內容
編程掙錢嗎 發布:2025-08-22 06:31:21 瀏覽:1000
敬請存儲 發布:2025-08-22 06:25:42 瀏覽:609
linuxphp7配置 發布:2025-08-22 06:17:01 瀏覽:414
shellftp腳本 發布:2025-08-22 06:11:57 瀏覽:796
sql資料庫打開 發布:2025-08-22 05:58:36 瀏覽:888
伺服器IP怎麼找回 發布:2025-08-22 05:41:28 瀏覽:606
手機百度怎樣上傳視頻 發布:2025-08-22 05:28:08 瀏覽:832
亂碼源碼 發布:2025-08-22 05:26:41 瀏覽:204
c語言中基本的數據類型 發布:2025-08-22 05:24:25 瀏覽:809
Android資料庫開源 發布:2025-08-22 05:18:02 瀏覽:631