国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

通過兩個例子講解PIVOT/UNPIVOT的用法

2024-07-21 02:42:03
字體:
來源:轉載
供稿:網友
使用過SQL Server 2000的人都知道,要想實現行列轉換,必須綜合利用聚合函數和動態SQL,具體實現起來需要一定的技巧,而在SQL Server 2005中,使用新引進的關鍵字PIVOT/UNPIVOT,則可以很容易的實現行列轉換的需求。

在本文中我們將通過兩個簡單的例子詳細講解PIVOT/UNPIVOT的用法。

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 testid name quarter profile----------- -------------- ----------- -----------1 a 1 10001 a 2 20001 a 3 40001 a 4 50002 b 1 30002 b 2 35002 b 3 42002 b 4 5500(8 row(s) affected)使用PIVOT將四個季度的利潤轉換成橫向顯示:select id,name,[1] as "一季度",[2] as "二季度",[3] as "三季度",[4] as "四季度"fromtestpivot(sum(profile)for quarter in([1],[2],[3],[4]))as pvtid name 一季度 二季度 三季度 四季度-------- --------- ----------- -------- ------- -------1 a 1000 2000 4000 50002 b 3000 3500 4200 5500(2 row(s) affected)

UNPIVOT的用法:

首先建立測試表,然后插入測試數據drop table testcreate table test(id int,name varchar(20), Q1 int, Q2 int, Q3 int, Q4 int)insert into test values(1,'a',1000,2000,4000,5000)insert into test values(2,'b',3000,3500,4200,5500)select * from testid name Q1 Q2 Q3 Q4-------- ------- --------- --------- -------- --------1 a 1000 2000 4000 50002 b 3000 3500 4200 5500(2 row(s) affected)使用UNPIVOT,將同一行中四個季度的列數據轉換成四行數據:select id,name,quarter,profilefromtestunpivot(profilefor quarter in([Q1],[Q2],[Q3],[Q4])) as unpvtid name quarter profile----------- ----------- ---------- -----------1 a Q1 10001 a Q2 20001 a Q3 40001 a Q4 50002 b Q1 30002 b Q2 35002 b Q3 42002 b Q4 5500(8 row(s) affected)

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 沂水县| 都江堰市| 达日县| 通州区| 潢川县| 陕西省| 界首市| 简阳市| 巴林左旗| 西畴县| 台南市| 康平县| 安龙县| 阿拉善左旗| 福鼎市| 涞水县| 徐闻县| 治多县| 五常市| 巫溪县| 长寿区| 子长县| 雅江县| 渭源县| 青龙| 定州市| 攀枝花市| 平陆县| 鹿邑县| 盱眙县| 永年县| 浪卡子县| 株洲县| 得荣县| 吉林省| 七台河市| 喜德县| 增城市| 共和县| 武鸣县| 屏东县|