表sales
查詢結果如下:
1、建表
CREATE TABLE [dbo].[sales](
[id] [int] IDENTITY(1,1) NOT NULL,
[year] [int] NULL,
[jidu] [int] NULL,
[jine] [int] NULL,
PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
2、插入數據
INSERT INTO sales(year, jidu, jine) VALUES(1991,1,11)
INSERT INTO sales(year, jidu, jine) VALUES(1991,2,22)
INSERT INTO sales(year, jidu, jine) VALUES(1991,3,33)
INSERT INTO sales(year, jidu, jine) VALUES(1991,4,44)
INSERT INTO sales(year, jidu, jine) VALUES(1992,1,55)
INSERT INTO sales(year, jidu, jine) VALUES(1992,2,66)
INSERT INTO sales(year, jidu, jine) VALUES(1992,3,77)
INSERT INTO sales(year, jidu, jine) VALUES(1992,4,88)
有兩種解決方法:
一、使用case when 實現:
SELECT
year as '年份',
max(CASE jidu WHEN 1 THEN jine END) AS '第一季度',
max(CASE jidu WHEN 2 THEN jine END) AS '第二季度',
max(CASE jidu WHEN 3 THEN jine END) AS '第三季度',
max(CASE jidu WHEN 4 THEN jine END) AS '第四季度'
FROM sales group by year
二、使用pivot函數:
使用pivot函數時須注意對升級到 SQL Server 2005 或更高版本的數據庫使用 PIVOT 和 UNPIVOT 時,必須將數據庫的兼容級別設置為 90 或更高。
語法介紹參考如下網址:
https://technet.microsoft.com/zh-cn/library/ms177410(v=sql.105).aspx
SQL語句如下:
select year as 年份,[1] as 第一季度,[2] as 第二季度,[3] as 第三季度,[4] as 第四季度
from (select year,jidu,jine from sales) as t1 pivot (SUM(jine) FOR jidu IN ([1],[2],[3],[4])) as a --'t1'和'a'這兩個別名必須得有要不會報錯。
執行結果如下: