Friday, January 31, 2014

Homework Answers Pivoting Lesson

Here are a few of the answers for the questions I had posted before regarding pivoting:

--My made up homework--
--1)
WITH freightav AS
(SELECT custid, shipperid, freight
FROM sales.orders)
SELECT custid, [1], [2], [3]
FROM freightav
PIVOT(AVG(freight) FOR shipperid IN ([1], [2], [3]) ) AS P
WHERE custid BETWEEN 5 AND 10

--2) My first try
WITH Pivotdata AS(
SELECT YEAR(orderdate) AS yr, shipperid, shippeddate
FROM sales.orders)
SELECT YEAR(orderdate) AS yr, [1], [2], [3]
FROM sales.orders
PIVOT(MAX(shippeddate) FOR shipperid IN ([1], [2], [3])) AS p

--2) Redone Correctly
WITH pivotdata AS(
SELECT YEAR(orderdate) AS yr, shipperid, shippeddate
FROM sales.orders)
SELECT yr, [1], [2], [3]
FROM pivotdata
PIVOT (MAX(shippeddate) FOR shipperid IN ([1], [2], [3])) AS p

--3) My version
WITH pivotdata AS(
SELECT custid, shipperid, orderid
FROM sales.orders
WHERE orderid IS NOT NULL)
SELECT custid, [1], [2], [3]
FROM pivotdata
PIVOT(COUNT(orderid) FOR shipperid IN([1], [2], [3])) AS P



No comments:

Post a Comment