測試數據:
create table StudentScore
(
Name varchar(12) NULL,
ClassName varchar(12) NULL,
Grade int NULL
)
INSERT INTO StudentScore(Name,ClassName,Grade)
VALUES
('張三','語文','78'),('張三','數學','79'),('張三','英語','80'),
('張三','物理','81'),('張三','政治','82'),
('李四','語文','84'),('李四','數學','85'),('李四','英語','86'),
('李四','物理','83'),('李四','政治','87'),
('王五','語文','89'),('王五','數學','82'),('王五','英語','90'),
('王五','物理','81'),('王五','政治','91')
創建完測試數據後,SELECT後的結果如圖:
要求寫一條SQL查詢語句,查詢結果如下列顯示
姓名 語文 數學 英語 物理 政治
張三 78 79 80 81 82
李四 83 84 85 86 87
王五 88 89 90 91 92
1 利用CASE WHEN關鍵字
SELECT Name,MAX(CASE ClassName WHEN '語文' THEN Grade ELSE 0 END)語文,
MAX(CASE ClassName WHEN '數學' THEN Grade ELSE 0 END)數學,
MAX(CASE ClassName WHEN '英語' THEN Grade ELSE 0 END)英語,
MAX(CASE ClassName WHEN '物理' THEN Grade ELSE 0 END)物理,
MAX(CASE ClassName WHEN '政治' THEN Grade ELSE 0 END)政治
FROM StudentScore GROUP BY Name
效果圖:
2 利用PIVOT運算符
SELECT Name,[語文],[數學],[英語],[物理],[政治]
FROM StudentScore
PIVOT
(
MAX(Grade)
FOR ClassName IN ([語文],[數學],[英語],[物理],[政治])
) AS PivotTable
PIVOT是是sql server 2005新特性。
SELECT <non-pivoted column>,
--不要聚合的列
[first pivoted column] AS <column name>,
[second pivoted column] AS <column name>,
...
[last pivoted column] AS <column name>
FROM
(<SELECT query that produces the data>)
AS <alias for the source query>
PIVOT
(
<aggregation function>(<column being aggregated>)
--聚合函數加將要轉置成行的列的數據
FOR
[<column that contains the values that will become column headers>] --要被轉置成行的列
IN ( [first pivoted column], [second pivoted column],
... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;