总结一下sql中的一列

时间:2013-11-19 12:53:00

标签: sql sql-server-2008 union

我有一个要求我想要以下结果集:

Type       Receipts Issues Balance
==================================
Purchase    10       0     10
Purchase    5        0     15
Sales       0        2     13  
Purchase    10       0     23
Sales       0        5     18

最后一栏sholud总结为Balance =(收据 - 问题)+余额

我的查询是:

SELECT type, 
       Isnull(receipts, 0)                         AS Receipts, 
       Isnull(issues, 0)                           AS Issues, 
       ( Isnull(receipts, 0) - Isnull(issues, 0) ) AS Balance 
FROM   (SELECT 'Purchasse' AS Type, 
               PBD.qty     AS Receipts, 
               NULL        AS Issues 
        FROM   tbl_purchasebillmain PB 
               JOIN tbl_purchasebilldetail PBD 
                 ON PBD.purchasebill_id = PB.record_id 
               JOIN tbl_product_master PM 
                 ON PM.record_id = PBD.product_id 
        UNION 
        SELECT 'Purchasse Return' AS Type, 
               NULL               AS Receipts, 
               PRD.qty            AS Issues 
        FROM   dbo.tbl_purchasereturnmain PR 
               JOIN dbo.tbl_purchasereturndetail PRD 
                 ON PRD.purchasereturnbill_id = PR.record_id 
               JOIN tbl_purchasebilldetail PBD 
                 ON PBD.record_id = PRD.purchasebilldetail_id 
               JOIN tbl_product_master PM 
                 ON PM.record_id = PBD.product_id) AS s 

1 个答案:

答案 0 :(得分:0)

我不确定你的意思(收据 - 问题)+余额,但我想你想要这个:

SELECT type, 
       sum(Isnull(receipts, 0))                         AS Receipts, 
       sum(Isnull(issues, 0))                           AS Issues, 
       sum(( Isnull(receipts, 0) - Isnull(issues, 0) )) AS Balance 
FROM   (SELECT 'Purchasse' AS Type, 
               PBD.qty     AS Receipts, 
               NULL        AS Issues 
        FROM   tbl_purchasebillmain PB 
               JOIN tbl_purchasebilldetail PBD 
                 ON PBD.purchasebill_id = PB.record_id 
               JOIN tbl_product_master PM 
                 ON PM.record_id = PBD.product_id 
        UNION 
        SELECT 'Purchasse Return' AS Type, 
               NULL               AS Receipts, 
               PRD.qty            AS Issues 
        FROM   dbo.tbl_purchasereturnmain PR 
               JOIN dbo.tbl_purchasereturndetail PRD 
                 ON PRD.purchasereturnbill_id = PR.record_id 
               JOIN tbl_purchasebilldetail PBD 
                 ON PBD.record_id = PRD.purchasebilldetail_id 
               JOIN tbl_product_master PM 
                 ON PM.record_id = PBD.product_id) AS s 
group by type