Thursday, August 21, 2008

PIVOT SQL-Server 2005 with sample

The PIVOT keyword is new in SQL 2005. It was designed for pivots and its syntax is more readable than a group of CASE statements. This next statement produces a report identical to the proceeding CASE Cross Tab. In the code below, SUM specifies the grid data and FOR dictates the horizontal axis, IN creates a filter for SUM to match.
YearSold Quarter Amount
#sales Table Data
2003 Q1 1.00
2003 Q2 2.00
2003 Q3 3.00
2003 Q4 4.00
2004 Q1 5.00
2004 Q2 6.00
2004 Q3 7.00
2004 Q4 8.00
2005 Q1 9.00
2005 Q2 10.00
2005 Q3 0.00
2005 Q4 0.00

PIVOT Query


SELECT * FROM #sales
PIVOT
(
SUM(Amount)
FOR Quarter
IN (Q1, Q2, Q3, Q4)
)
AS p

YearSold Q1 Q2 Q3 Q4
2003 1.00 2.00 3.00 4.00
2004 5.00 6.00 7.00 8.00
2005 9.00 10.00 0.00 0.00

1 comment:

Alex said...

Solving problems associated with mdf files you may trust sql database recovery. It doesn't modify source data of .mdf files during recovering, works under any PC software configuration and Windows OS. The application uses modern methods of recovering sql data.