Search

Tuesday, November 16, 2010

Rotate a table in SQL Server

Rows to Column

Source Table

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

Result Table

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


SQL

SELECT year=q.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

Columns to Row

Source Table

ID | RefDate |Rcvd Date
----------------------------
1 | 01/01/04| 02/01/04
2 | 05/01/04| 07/01/04
3 | 07/01/04| 12/01/04

Result Table

ID | Date | Type
----------------------------
1 | 01/01/04| RefDate
1 | 02/01/04| RcvdDate
2 | 05/01/04| RefDate
2 | 07/01/04| RcvdDate
3 | 07/01/04| RefDate
3 | 12/01/04| RcvdDate

SQL

SELECT ID, RefDate, 'RefDate' AS Type FROM myTable
UNION

SELECT ID, RcvdDate, 'RcvdDate' AS Type FROM myTable

No comments:

Post a Comment