2009-12-24 71 views
1

我有一個訂單明細表。將總計添加到組

我想要做的是創造100個查詢,以顯示

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

謝謝。

回答

4

額外的列是容易的,只是創建在被定義爲兩個exsting的乘積的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 
1

我不知道如果這樣做的所有,在單個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 

還沒有嘗試過,雖然本。