显示所有小计和每个帐单的总计

时间:2013-12-15 05:14:50

标签: sql sqlite

我对此结果有疑问:

billno painter_id painter_rate painter_subtotal sum_1
2      2          5            30               30
7      2          20           160              255
7      2          20           80               255
7      2          5            15               255

使用以下SQL:

SELECT a1.billno, a1.painter_id, a1.painter_rate, 
    a1.painter_subtotal, a2.painter_subtotal AS sum_1 
FROM voucher_paint_detail AS a1 LEFT OUTER JOIN 
    (SELECT billno,sum(painter_subtotal) AS painter_subtotal 
    FROM voucher_paint_detail where painter_id='BMLWA' GROUP BY billno) AS a2
ON a2.billno = a1.billno
WHERE a1.painter_id = '2'

在这张桌子上:

CREATE TABLE [voucher_paint_detail] (
    [srno] INTEGER NULL,
    [painter_id] TEXT NULL,
    [painter_rate] REAL NULL,
    [paint_quantity] INTEGER NULL,
    [painter_subtotal] REAL NULL,
    [transaction_id] INTEGER NULL,
    PRIMARY KEY ([srno])
)

我希望数据看起来像

billno painter_id painter_rate painter_subtotal sum_1
2      2          5            30               30
7      2          20           160   
7      2          20           80    
7      2          5            15               255

1 个答案:

答案 0 :(得分:0)

你的JOIN相当冗长,所以让我们用SELECT子句中的相关子查询重写你的查询(含义相同,但这样我们就可以避免计算不感兴趣的记录的总和):

SELECT billno,
       painter_id,
       painter_rate,
       painter_subtotal,
       (SELECT SUM(painter_subtotal)
        FROM voucher_paint_detail
        WHERE billno     = a1.billno
          AND painter_id = a1.painter_id
       ) AS sum_1
FROM voucher_paint_detail AS a1
WHERE painter_id = 'BMLWA'

为了能够将账单的最后记录与其他记录区分开来,我们必须对一张账单的所有记录进行一些排序。 在这里,我使用srno

SELECT billno,
       painter_id,
       painter_rate,
       painter_subtotal,
       (SELECT SUM(painter_subtotal)
        FROM voucher_paint_detail
        WHERE billno     = a1.billno
          AND painter_id = a1.painter_id
       ) AS sum_1
FROM voucher_paint_detail AS a1
WHERE painter_id = 'BMLWA'
ORDER BY billno,
         srno

然后,账单的最后一条记录是一张记录,其中没有其他记录存在相同的账单编号但更高的srno

SELECT billno,
       painter_id,
       painter_rate,
       painter_subtotal,
       CASE WHEN NOT EXISTS (SELECT srno
                             FROM voucher_paint_detail
                             WHERE billno     = a1.billno
                               AND painter_id = a1.painter_id
                               AND srno       > a1.srno)
            THEN (SELECT SUM(painter_subtotal)
                  FROM voucher_paint_detail
                  WHERE billno     = a1.billno
                    AND painter_id = a1.painter_id)
            ELSE NULL
       END AS sum_1
FROM voucher_paint_detail AS a1
WHERE painter_id = 'BMLWA'
ORDER BY billno,
         srno

注意:EXISTS子查询不太可能比SUM子查询更高效,因此您不太可能保存任何内容。