Tuesday, July 24, 2012

More on pivot tables - adding row totals to a pivot table

Below is a query that retrieves monthly order count for each customer and displays it in tabular form using pivot table. Second column displayed is the row total for all the months for the current year.

As an example I used Northwind database.


SELECT CompanyName, ISNULL([Jan],0) + ISNULL([Feb],0) + ISNULL([Mar],0) + ISNULL([Apr],0) + ISNULL([May],0) + ISNULL([Jun],0) + ISNULL([Jul],0) + ISNULL([Aug],0) + ISNULL([Sep],0) + ISNULL([Oct],0) + ISNULL([Nov],0) + ISNULL([Dec],0) As [Year Total],[Jan], [Feb], [Mar], [Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec] 
FROM (SELECT c.CompanyName,c.CustomerID,o.OrderID, SUBSTRING(DateName(MONTH,o.OrderDate), 0,4) As OrderMonth FROM Orders as o INNER JOIN Customers as c ON o.CustomerID=c.CustomerID WHERE YEAR(OrderDate)=Year(GETDATE())) Data
PIVOT(
COUNT(OrderID) 
FOR OrderMonth IN([Jan], [Feb], [Mar], [Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec])) As MonthlyOrderQty


The result displayed will be something like this:

Company Name Year Total Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Alfreds Futterkiste 3 1 0 1 1 0 0 0 0 0 0 0 0
Ana Trujillo Emparedados y helados 1 0 0 1 0 0 0 0 0 0 0 0 0
Antonio Moreno Taquería 1 1 0 0 0 0 0 0 0 0 0 0 0
Around the Horn 4 0 1 2 1 0 0 0 0 0 0 0 0
Berglunds snabbköp 5 2 2 1 0 0 0 0 0 0 0 0 0
Blauer See Delikatessen 3 1 0 1 1 0 0 0 0 0 0 0 0
Blondesddsl père et fils 1 1 0 0 0 0 0 0 0 0 0 0 0

No comments:

Post a Comment