[英]Add total to group
我有一個訂單明細表。
我想做的是創建1個查詢以顯示
OrderNumber | SKU | QTY | Price | Line Total |
1 SKU1 1 10.00 10.00
1 ---- 0 0.00 10.00
2 SKU1 2 10.00 20.00
2 SKU2 3 1.50 4.50
2 ---- 0 0.00 24.50
我的意思是我需要為每個訂單添加另一行,並將總金額添加到文本文件中。
我有SQL Server 2005
謝謝。
額外的列很容易,只需在sql中創建另一個輸出列即可,該輸出列定義為兩個現有屬性的乘積
Select OrderNumber, SKU, QTY, Price, Qty * Price as LineTotal
From Table ...
第二部分,添加小計行,可以使用關鍵字Rollup
或與匯總查詢合並來完成
Select OrderNumber, SKU, QTY, Price,
Qty * Price as LineTotal
From Table
Union
Select OrderNumber, null SKU, null Qty, null Price,
Sum( Qty * Price ) as LineTotal
From Table
Group By OrderNumber
Order By OrderNumber, Case When SKU Is Null then 1 Else 0 End
我不確定在單個SQL中完成所有操作是否是個好主意,但是您可以嘗試使用並集:
SELECT *
FROM (
SELECT ordernumber, sku, qty, price, qty*price line_total
FROM order_details
UNION
SELECT ordernumber, '---' sku, 0 qty, 0 price, SUM(qty*price)
FROM order_details
GROUP BY ordernumber
)
ORDER BY ordernumber, sku
雖然沒有嘗試過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.