2009-12-24 69 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 

还没有尝试过,虽然本。