PIVOT columns in SQL Server with their SUM

六眼飞鱼酱① 提交于 2020-01-15 12:23:33

问题


In reference to my previous Question . With these changes in the tables : (*) are used to mark the changes in the tables.

Products Table

prod_ID   - int
prod_Name - varchar(100)
prod_Code - varchar(100)
*prod_Price- float 

Orders Table

ord_ID  - int
ord_Qty - int
prod_ID - int
cus_ID  - float
*ord_PurchaseType - varchar(100)

Given that all items are priced as 10 dollars each. I want to make the final report to be something like this.

Currently, I'm using something like this: SUM(CASE WHEN ord_PurchaseType = 'cash' THEN prod_Price ELSE 0 END) to get the data, It works when I run in not inside the SET @query = N' ... query. Aside from that It is having an error saying that it has an invalid column named cash. I also tried putting the word cash in a variable but it still produces the same error.


回答1:


Okay this one was a bit more challenging but building on our last answer. The difference with what you want to do here is essentially aggregate 2 different values into the same report. Summing the product quantities and also summing the cash payments. You can't do it all in a single pivot statement, but you can do them separately and then join them together.

See SQL Fiddle

So here you see our original Pivot at the top which has been wrapped in a Common Table Expression (CTE) called ProductQuantities. We have then added a new CTE for the payments which you will notice has a slightly different Group By as we are only interested in the Cash Payments by Customer. Finally we join the results of both queries together on the customer to get our final result set.

SET @query = N'WITH ProductQuantities As (
SELECT cus_Name,'+ @colsForSelect +' 
FROM (    
     Select cus_Name, prod_Name, SUM(ord_Qty) as sum_ord_Qty
     from Orders o
     inner join Customers c on c.cus_ID = o.cus_ID
     inner join Products p on p.prod_ID = o.Prod_ID
     GROUP BY cus_Name, prod_Name
) p 
PIVOT (MAX([sum_ord_Qty]) FOR prod_Name IN ( '+ @colsForPivot +' )) 
AS pvt),

CustomerPayments As (
Select cus_Name, SUM(Case When ord_PurchaseType = ''cash'' then p.prod_Price * o.[ord_Qty] else 0 End) as [Cash Payments]
     from Orders o
     inner join Customers c on c.cus_ID = o.cus_ID
     inner join Products p on p.prod_ID = o.Prod_ID
     GROUP BY cus_Name
)

Select pq.*, cp.[Cash Payments]
FROM ProductQuantities pq
INNER JOIN CustomerPayments cp on pq.cus_Name = cp.cus_Name'



回答2:


Try this one .

SUM(CASE WHEN ord_PurchaseType = ''cash'' ....

How do I escape a single quote in SQL Server?



来源:https://stackoverflow.com/questions/30975910/pivot-columns-in-sql-server-with-their-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!