使用某些列的总计向SQL查询结果添加行

时间:2015-06-30 22:17:02

标签: sql sql-server sum row totals

我有一个SQL查询

select * from orderTable

返回:

enter image description here

我希望查询返回另一行,其中orderId ='Total',GrossAmt,Payments,NetAmt的总和,其余字段为空,如下所示:

enter image description here

我尝试了什么:

select isnull(OrderId, 'Total') as OrderId, GrossAmt
from    (
        select OrderId, SUM(GrossAmt) as GrossAmt
        from orderTable
        group by OrderId with rollup
    ) as OT

哪个会返回最后一行的总和和GrossAmt的总和,但是当我尝试添加时,比如说StoreId:

select isnull(OrderId, 'Total') as OrderId, GrossAmt, StoreId
    from    (
            select OrderId, SUM(GrossAmt) as GrossAmt, StoreId
            from orderTable
            group by OrderId, StoreId with rollup
        ) as OT

然后我得到两倍的结果,每行只有一个副本,只有StoreId的空值。

我只是想在上面的查询中切换OrderId和StoreId的位置,这给了我最接近的结果。我有我想要的,只有底部总共有2行,其中一行有一个null StoreId。

2 个答案:

答案 0 :(得分:2)

您可以使用UNION将其设为一个表:

     select * from
        (
        select cast(OrderId as Varchar) as OrderId, Custname, GrossAmt, Payments, NetAmt, StoreId, StaffName
        from orderTable
        UNION
        (select 'Total' as OrderId, Null as Custname, 
            Sum(GrossAmt) As GrossAmt, 
            Sum(Payments) As Payments, 
            Sum(NetAmt) As NetAmt, Null as StoreId, Null as StaffName
        from orderTable) 
        ) a

请注意,强制转换在OrderId列中包含Total fit一词

答案 1 :(得分:1)

SELECT  ISNULL(OrderId, 'Total') as OrderId, GrossAmt, NULL AS storeId
FROM    (
        SELECT  OrderId, SUM(GrossAmt) as GrossAmt
        FROM    orderTable
        GROUP BY
                OrderId WITH ROLLUP
        ) AS OT