如何在sql查询中添加表底部的行?

时间:2014-03-12 18:42:55

标签: sql sql-server

我有选择查询,我想要添加包含借方和贷方列之和的表格底部。

我的SQL查询如下:

SELECT * 
FROM 
    (SELECT 
        so.OrderDate ,'Sales' As VoucherType,'' AS VoucherNo,
        a.Total As Debit, NULL As Credit 
    FROM SalesOrder so 
    INNER JOIN
       (SELECT 
           SalesOrderId, SUM(SubTotal) AS Total 
        FROM SalesOrderDetails 
        GROUP BY SalesOrderId) AS a ON so.SalesOrderId = a.SalesOrderId

        UNION ALL

        SELECT  
           v.VoucherDate As OrderDate, 'Receipt' AS VoucherType,
           v.VoucherNumber AS VoucherNo, NULL AS Debit,
           v.Amount AS Credit 
        FROM Vouchers v) AS ledger 
ORDER BY 
     OrderDate ASC

我的查询输出位于下图中。

Here I have attached image of my query result and i want add row end of table. it row contains sum of debit and credit.

1 个答案:

答案 0 :(得分:2)

您可以使用grouping sets执行此操作。首先,将查询重新排列为聚合查询。聚合不做任何事情,但总需要它们。

然后使用group by grouping sets ()定义各个组:

SELECT OrderDate, VoucherType, VoucherNo, sum(Debit) as Debit, sum(Credit) as Credit
FROM (SELECT so.OrderDate ,'Sales' As VoucherType, '' AS VoucherNo,
             a.Total As Debit, NULL As Credit
      from SalesOrder so inner join
           (SELECT SalesOrderId,sum(SubTotal) AS Total
            FROM SalesOrderDetails 
            group by SalesOrderId)as a on so.SalesOrderId = a.SalesOrderId
            UNION ALL
            SELECT v.VoucherDate As OrderDate, 'Receipt' AS VoucherType,
                   v.VoucherNumber AS VoucherNo,NULL AS Debit ,
                   v.Amount AS Credit from Vouchers v
           ) ledger
GROUP BY GROUPING SETS ((OrderDate, VoucherType, VoucherNo), ())
ORDER BY OrderDate ASC