Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Nicer way of doing this
Message
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Stored procedures, Triggers, UDFs
Versions des environnements
SQL Server:
SQL Server 2014
Application:
Desktop
Divers
Thread ID:
01612941
Message ID:
01612943
Vues:
65
>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.
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform