文章詳情頁(yè)
SQL Server使用PIVOT與unPIVOT實(shí)現(xiàn)行列轉(zhuǎn)換
瀏覽:248日期:2023-03-06 14:25:24
一、sql行轉(zhuǎn)列:PIVOT
1、基本語(yǔ)法:
create table #table1 ( id int ,code varchar(10) , name varchar(20) );goinsert into #table1 ( id,code, name ) values ( 1, "m1","a" ), ( 2, "m2",null ), ( 3, "m3", "c" ), ( 4, "m2","d" ), ( 5, "m1","c" );goselect * from #table1;--方法一(推薦)select PVT.code, PVT.a, PVT.b, PVT.c from #table1 pivot(count(id) for name in(a, b, c)) as PVT;--方法二with P as (select * from #table1)select PVT.code, PVT.a, PVT.b, PVT.c from Ppivot(count(id) for name in(a, b, c)) as PVT;drop table #table1;
結(jié)果:

2、實(shí)例:

3、傳統(tǒng)方式:(先匯總拼接出所需列的字符串,再動(dòng)態(tài)執(zhí)行轉(zhuǎn)列)
先查詢出要轉(zhuǎn)為列的行數(shù)據(jù),再拼接字符串。
create table #table1 ( id int ,code varchar(10) , name varchar(20) );goinsert into #table1 ( id,code, name ) values ( 1, "m1","a" ), ( 2, "m2",null ), ( 3, "m3", "c" ), ( 4, "m2","d" ), ( 5, "m1","c" );goselect * from #table1;declare @strCN nvarchar(100);select @strCN = isnull(@strCN + ",", "") + quotename(name) from #table1 group by name ;print @strCN --‘[a],[c],[d]"declare @SqlStr nvarchar(1000);set @SqlStr = N"select * from #table1 pivot ( count(ID) for name in (" + @strCN + N") ) as PVT";exec ( @SqlStr );drop table #table1;結(jié)果:

二、sql列轉(zhuǎn)行:unPIVOT:
基本語(yǔ)法:
create table #table1 (id int,code varchar(10),name1 varchar(20),name2 varchar(20),name3 varchar(20));goinsert into #table1(id, name1, name2, code, name3)values(1, "m1", "a1", "a2", "a3"), (2, "m2", "b1", "b2", "b3"), (4, "m1", "c1", "c2", "c3");goselect * from #table1;--方法一select PVT.id, PVT.code, PVT.name, PVT.val from #table1 unpivot(val for name in(name1, name2, name3)) as PVT;--方法二with P as (select * from #table1)select PVT.id, PVT.code, PVT.name, PVT.val from P unpivot(val for name in(name1, name2, name3)) as PVT;drop table #table1;
結(jié)果:

實(shí)例:

到此這篇關(guān)于SQL Server使用PIVOT與unPIVOT實(shí)現(xiàn)行列轉(zhuǎn)換的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持。
標(biāo)簽:
MsSQL
相關(guān)文章:
1. SQL Server 2008數(shù)據(jù)庫(kù)引擎優(yōu)化顧問(wèn)與索引優(yōu)化向?qū)еg的差別2. sql server 2005中的DDL觸發(fā)器3. 如何禁止遠(yuǎn)程訪問(wèn)sql server4. The MySQL server is running with the --read-only option so it cannot execute this statement5. sql server里面可能經(jīng)常會(huì)用到的日期格式轉(zhuǎn)換方法6. SQL Server數(shù)據(jù)庫(kù)超級(jí)管理員賬號(hào)防護(hù)知識(shí)7. 終級(jí)解決SQL Server 2005 未正常卸載,重新安裝問(wèn)題8. SQL server分頁(yè)的四種方法思路詳解(最全面教程)9. SQL Server EXEC和sp_executesql的區(qū)別10. sql server修改表格數(shù)據(jù)的方法
排行榜

網(wǎng)公網(wǎng)安備