sqlserver (行轉列)pivot與(列轉行)unpivot的應用

sqlserver 中PIVOT(行轉列)與UNPIVOT(列轉行)使用

create table sellmessage(
id int  identity(1,1) primary key,
name varchar(50) null,
oneday money null,
twoday money null,
thrday money null
)

insert into sellmessage values('瓊其',3000,3000,2000),('寶勝',1000,2000,2000),('廣勝原',3000,4000,1000)
select * from sellmessage

現在有一個表

xxx公司每天營業表

爲了方便 我們使用unpivot先展示一下列轉行

個人總結:列轉行 先 起兩個別名,一個是之前列總體的分類 比如 oneday,twoday…可爲第*天 另一個是之前列下數據點比如金額 然後哪個是分類哪個就在for裏,把之前的列寫在in裏
具體代碼如下

select  name,[第*天],[金額]  from
(select name,oneday,twoday,thrday from sellmessage) as y
unpivot(
[金額]
for[第*天]
in([oneday],[twoday],[thrday])
) as ft

這裏as後面可以隨意命名
在這裏插入圖片描述

之後行轉列pivot

with sell as( /*創建臨時表 臨時表必須和使用臨時表的語句一起執行纔有效*/
select name,[days],[moneys] from (select name,oneday,twoday,thrday from sellmessage) as y
unpivot(
[moneys]
for[days]
in([oneday],[twoday],[thrday])
) as ft
/**列轉行***/
)
select name,[oneday],[twoday],[thrday] from(select name,days,moneys/**或 「*」  **/ from sell)as u
pivot(
sum(moneys)/** 行轉列 列的數據點(值)**/
for[days]     /**要轉的列**/
in([oneday],[twoday],[thrday])/**要轉列的name**/
)as e
/*行轉列***/

最終效果又回到了之前
**行轉列總結:**1,先清楚自己要到的條件
2,清楚原表 哪個列下的數據點 當新表的列(比如oneday,twoday…)
3,清楚 原表 哪個列下的數據點 當新表列的值(比如1000,2000…)
4,依次寫入pivot裏

這裏是公式
不斷的努力就是更好的明天