Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Nicer way of doing this
Message
General information
Forum:
Microsoft SQL Server
Category:
Stored procedures, Triggers, UDFs
Environment versions
SQL Server:
SQL Server 2014
Application:
Desktop
Miscellaneous
Thread ID:
01612941
Message ID:
01612943
Views:
67
>Hi all, the query below produces a count and summation of monies by month, it works perfectly but *pretty it ain't*, anyone know of a *nicer* way of doing this ?

Hi, Pete,

In general, you might want to look at the PIVOT statement. Here is a basic example - it spreads data out by the quarter, not the month, but hopefully you'll see the idea:
use adventureworks2012
go
;with TempCTE as
     ( select sm.Name as ShipName, DatePart(q,OrderDate) as QtrNum, sum(TotalDue) as TotDue
         from Purchasing.PurchaseOrderHeader  POH
	        join Purchasing.ShipMethod SM on POH.ShipMethodID = sm.ShipMethodID
	        where year(OrderDate) = 2008
	     group by  SM.Name, datepart(q, orderDate) )

   select ShipName,  [1] as Q1, [2] as Q2, [3] as Q3     , [4] as Q4
      from TempCTE
      PIVOT (   SUM(TotDue) for QtrNum in ( [1], [2], [3], [4])) Temp   
Now, you've got an added twist - you want to have multiple aggregations (a count and a sum) for each month being spread across the columns. There are different ways you can do it - I've seen people use combinations of CROSS APPLY and other language features with PIVOT.

Actually, I think Naomi has posted solutions/blog posts in the past on this (multiple aggregations with PIVOT) and so I'll let her jump in if she has an example. If not, I'll post one later.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform