大网数据广告活动
数据库与应用安全

Rotate a table in SQL Server

· 52CE 我爱测

This article describes how to rotate a table in SQL Server.

This article describes how to rotate a table in SQL Server.

Original product version:   SQL Server
Original KB number:   175574

Summary

This article describes how to rotate a SQL Server table. Suppose you have a table that is named QTRSALES. The table has the columns YEAR, QUARTER, and AMOUNT with the data in the following format.

Note: There is no row for the fourth quarter of 1996:

Year Quarter Amount
1995 1 125,000.90
1995 2 136,000.75
1995 3 212,000.34
1995 4 328,000.82
1996 3 728,000.35
1996 2 422,000.13
1996 1 328,000.82

Now, suppose you want to rotate the table so that you can see the data in the following format:

YEAR Q1 Q2 Q3 Q4
1995 125,000.90 136,000.75 212,000.34 328,000.82
1996 328,000.82 422,000.13 728,000.35 0.00

The query that you would use to rotate the table is in the next section of this article.

Sample query to rotate the table

Here's the query that you would use to rotate the table:

SELECT YEAR,
Q1= ISNULL((SELECT AMOUNT FROM QTRSALES WHERE QUARTER = 1 AND YEAR =
Q.YEAR),0),
Q2= ISNULL((SELECT AMOUNT FROM QTRSALES WHERE QUARTER = 2 AND YEAR =
Q.YEAR),0),
Q3= ISNULL((SELECT AMOUNT FROM QTRSALES WHERE QUARTER = 3 AND YEAR =
Q.YEAR),0),
Q4= ISNULL((SELECT AMOUNT FROM QTRSALES WHERE QUARTER = 4 AND YEAR =
Q.YEAR),0)
FROM QTRSALES Q
GROUP BY YEAR

Query for large tables

For large tables, this query will be faster:

SELECT YEAR,
SUM(CASE quarter WHEN 1 THEN amount ELSE 0 END) AS Q1,
SUM(CASE quarter WHEN 2 THEN amount ELSE 0 END) AS Q2,
SUM(CASE quarter WHEN 3 THEN amount ELSE 0 END) AS Q3,
SUM(CASE quarter WHEN 4 THEN amount ELSE 0 END) AS Q4
FROM qtrsales q
GROUP BY YEAR

Reference

FROM - Using PIVOT and UNPIVOT

Source: Microsoft Learn / IT Pro troubleshooting by Microsoft and contributors. Documentation licensed CC BY 4.0. Code samples are covered by the MIT License. Converted from Markdown, with links normalized and embedded media omitted.

资料来源与适用范围

资料来源
Microsoft Learn / IT Pro troubleshooting
适用范围
See source applicability · Source date 11/03/2020
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 4.0 (documentation), MIT (code samples)

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。