日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

pivot 与 unpivot 函数是SQL05新提供的2个函数

發布時間:2023/12/2 数据库 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 pivot 与 unpivot 函数是SQL05新提供的2个函数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

pivot 與 unpivot 函數是SQL05新提供的2個函數 ?

------------------------------------------------------------------------------

pivot函數:

create table test(id int,name varchar(20),quarter int,profile int)
insert into test values(1,'a',1,1000)
insert into test values(1,'a',2,2000)
insert into test values(1,'a',3,4000)
insert into test values(1,'a',4,5000)
insert into test values(2,'b',1,3000)
insert into test values(2,'b',2,3500)
insert into test values(2,'b',3,4200)
insert into test values(2,'b',4,5500)

?

select * from test????--創建表test

?

?

現在需要把quarter 從1列數據變成4列數據??效果如:

?

?

把一列拆成幾列這時候就能使用pivot函數很簡單的實現

?

select * from test
pivot
(
?sum([profile]) for [quarter]
?in
?([1],[2],[3],[4])
)
as
s

注:使用pivot把一列拆成幾列時 需要后面as取個別名 這是固定的格式 同時如 for前是必須使用聚合函數的

當然不使用pivot函數也可以得到相同效果 只是代碼長切效率低 但容易理解

select id,[name],
'1'=(select sum([profile]) from test where id=a.id and quarter=1),
'2'=(select sum([profile]) from test where id=a.id and quarter=2),
'3'=(select sum([profile]) from test where id=a.id and quarter=3),
'4'=(select sum([profile]) from test where id=a.id and quarter=4)
from test as a
group by id,name

?

-----------------------------------------------------------------------------------------

unpivot函數 顧名思義 他就是把幾列合并到1列中去

create table test1(id int,name varchar(20), Q1 int, Q2 int, Q3 int, Q4 int)

insert into test1 values(1,'a',1000,2000,4000,5000)
insert into test1 values(2,'b',3000,3500,4200,5500)

?

select * from test1 --創建test1表

我們要把Q1 Q2 Q3 Q4合到1列 季度列中去 如效果:

?

?

使用unpivot可以很簡單的實現

select id ,[name],[jidu],[xiaoshou] from test1
unpivot
(
?xiaoshou for jidu in
?([q1],[q2],[q3],[q4])
)
as f

注:同樣需要使用as取別名同樣是固定的格式 unpivot函數中沒有聚合函數?xiaoshou和jidu列都是原來沒有的 jidu表由原來的Q1 Q2 Q3 Q4組成?

?

同樣的不使用unpivot也可以實現以上的功能

select id,[name],
jidu='Q1',
xiaoshou=(select Q1 from test1 where id=a.id)
from test1 as a
union
select id,[name],
jidu='Q2',
xiaoshou=(select Q2 from test1 where id=a.id)
from test1 as a
union
select id,[name],
jidu='Q3',
xiaoshou=(select Q3 from test1 where id=a.id)
from test1 as a
union
select id,[name],
jidu='Q4',
xiaoshou=(select Q4?from test1 where id=a.id)
from test1 as a

轉載于:https://www.cnblogs.com/sukhoi/p/7434882.html

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的pivot 与 unpivot 函数是SQL05新提供的2个函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。