• I appreciate that this is an example for an exam, and learning how to PIVOT (and UNPIVOT) is important.

    I haven't redone the performance testing recently, but from memory there was a performance issue with pivot which meant that you were actually better off doing a CASE statement to get the same values. Is that still valid, or have they fixed PIVOT?

    So your query becomes something like this:

    DECLARE

    @StartDate DATE

    , @EndDate DATE

    SET @StartDate = '2005-01-01'

    SET @EndDate = '2006-12-31'

    SELECT

    YEAR(OrderDate) AS OrderYear

    , TerritoryID

    , SUM(CASE WHEN MONTH(OrderDate) BETWEEN 1 AND 3 THEN 1 ELSE 0 END) AS [1]

    , SUM(CASE WHEN MONTH(OrderDate) BETWEEN 4 AND 6 THEN 1 ELSE 0 END) AS [2]

    , SUM(CASE WHEN MONTH(OrderDate) BETWEEN 7 AND 9 THEN 1 ELSE 0 END) AS [3]

    , SUM(CASE WHEN MONTH(OrderDate) BETWEEN 10 AND 12 THEN 1 ELSE 0 END) AS [4]

    FROM Sales.SalesOrderHeader

    WHERE OrderDate >= @StartDate

    AND OrderDate <= @EndDate

    GROUP BY YEAR(OrderDate), TerritoryId

    ORDER BY YEAR(OrderDate), TerritoryId