PIVOT Data in Yukon (RIP Case and Rozenshtein)
Let’s face it, users usually want to see data in tabular format, which is a bit of a challenge when we usually store data in a highly relational form. PIVOT is a new TSQL operator that you can specify in your FROM clause to rotate rows into columns and create a traditional “Crosstab” query without using CASE, Rozenshtein or subqueries. You have always been able to do this easily in Access with Pivot and Transform, but SQL Server was always a step behind.
Using PIVOT is easy. First in your select statement you need to specify the values you want to pivot on, in the following example, we will use the Year of the Order. Our FROM clause looks normal except for the PIVOT part. The PIVOT statement creates the value we plan on showing in the rows of the newly created columns, in this case I am using the aggregate SUM of the TotalAmount (a calculated field in our FROM clause). Then we have to use the FOR operator to list the values we are going to Pivot on in the OrdersYear column. The example is shown here:
SELECT CustomerID,  AS 'Y1996',  AS 'Y1997',  AS 'Y1998',  as 'Y1999'
(SELECT CustomerID,OD.UnitPrice * OD.Quantity - OD.Discount AS TotalAmt,
Year(dbo.Orders.OrderDate) as OrdersYear
FROM dbo.Orders INNER JOIN dbo.[Order Details] As OD
ON dbo.Orders.OrderID = OD.OrderID)
FOR OrdersYear IN(, , , )
) AS XTabData
Order BY CustomerID
The results look like this:
That is all there is to it. Of course this is a real simple example to show you the new concept, you can then of course get more sophisticated aggregates and even use Common Table Expressions in the FROM clause. Also you can use the UNPIVOT operator to normalize data that is already pivoted.
See my article on SQLJunkies.com.
Page rendered at Thursday, April 9, 2020 11:52:01 PM (Eastern Daylight Time, UTC-04:00)
The opinions expressed herein are my own personal opinions and do not represent
my employer's view in anyway.