我正在使用AdventureWorks2014数据库并使用以下查询。
select
SUM(Purchasing.PurchaseOrderDetail.OrderQty) as 'Total Quantity',
SUM(Purchasing.PurchaseOrderDetail.LineTotal) as 'Total Amount',
Purchasing.PurchaseOrderHeader.VendorID
from Purchasing.PurchaseOrderDetail
inner join Purchasing.PurchaseOrderHeader
on Purchasing.PurchaseOrderDetail.PurchaseOrderID = Purchasing.PurchaseOrderHeader.PurchaseOrderID
group by Purchasing.PurchaseOrderHeader.VendorID, DATEPART(year,Purchasing.PurchaseOrderHeader.OrderDate)
order by Purchasing.PurchaseOrderHeader.VendorID
这给了我以下输出。
|------------------------------------|
|Total Quantity|Total Amount|VendorID|
|15 |694.1655 | 1492|
|288 |12370.239 | 1492|
|45 |1931.7375 | 1492|
|180 |7682.6295 | 1492|
|9350 |150404.1 | 1494|
|1650 |26541.9 | 1494|
|550 |8847.3 | 1494|
|16500 |265419 | 1494|
|------------------------------------|
据我所知,这是每个供应商的每年数据,即2011,2012,2013和2014年的数据。这就是为什么每个供应商重复4次。
我需要将这些年中的每一年作为输出中的单独列,如下所示。
|--------------------------------------------------------------------------------|
|Total Quantity|Total Amount|VendorID|2011Amount|2012Amount|2013Amount|2014Amount|
|--------------------------------------------------------------------------------|
有什么想法吗?
答案 0 :(得分:1)
透视方法,确保在旋转之前首先准备查询。
;WITH cte AS (
SELECT
DATEPART(year,poh.OrderDate) as [Year]
,SUM(pod.OrderQty) OVER (PARTITION BY DATEPART(year,poh.OrderDate)) as TotalQuantity
,SUM(pod.LineTotal) OVER (PARTITION BY DATEPART(year,poh.OrderDate)) as TotalAmount
,pod.LineTotal as Amount
FROM
Purchasing.PurchaseOrderDetail pod
INNER JOIN Purchasing.PurchaseOrderHeader poh
ON pod.PurchaseOrderId = poh.PurchaseOrderId
)
SELECT *
FROm
cte
PIVOT (
SUM(Amount)
FOR [Year] IN ([2011],[2012],[2013],[2014])
) p
条件聚合方法
SELECT
SUM(pod.OrderQty) as TotalQuantity
,SUM(pod.LineTotal) as TotalAmount
,SUM(CASE WHEN DATEPART(year,poh.OrderDate) = 2011 THEN pod.LineTotal ELSE 0 END) as [2011Amount]
,SUM(CASE WHEN DATEPART(year,poh.OrderDate) = 2012 THEN pod.LineTotal ELSE 0 END) as [2012Amount]
,SUM(CASE WHEN DATEPART(year,poh.OrderDate) = 2013 THEN pod.LineTotal ELSE 0 END) as [2013Amount]
,SUM(CASE WHEN DATEPART(year,poh.OrderDate) = 2014 THEN pod.LineTotal ELSE 0 END) as [2014Amount]
FROM
Purchasing.PurchaseOrderDetail pod
INNER JOIN Purchasing.PurchaseOrderHeader poh
ON pod.PurchaseOrderId = poh.PurchaseOrderId
在这种情况下,我认为我会使用条件聚合方法.....请注意我使用表别名来引用表而不是继续输入长名称,这是一个很好的习惯。< / p>
这个确切的代码当然是未经测试的,因为您没有包含测试数据和所需的结果,但这些技术是最标准的方法。请注意,当聚合涉及多于1列时,通常最容易进行条件聚合。