一个对多个具有不同主键的表使用Sum和Group By的SQL

时间:2019-01-01 03:33:37

标签: sql sql-server-2014

假设我有以下表格:inv_mast,po_hdr,po_line和vessel_receipts_line 而且我有以下数据:

inv_mast.inv_mast_uid
12
2852

po_hdr.po_no
1000019
1000118

po_line.po_no|line_id|po_line_uid|inv_mast_uid
1000019      |1      |234        |12
1000118      |1      |646        |2852
1000118      |2      |648        |2852

vessel_receipts_line.po_line_uid|container_qty_received|row_status_flag
234                             |9700                  |702
646                             |320000                |702
646                             |2710000               |701
648                             |3250000               |702

现在,我尝试对每个po_no + inv_mast_uid + row_status_flag的container_qty_received求和,应该为702。 例如,我预期的结果是

po_no  |inv_mast_uid|container_qty_received|row_status_flag
1000019|12          |9700                  |702
1000118|2852        |3570000               |702
1000118|2852        |2710000               |701

我尝试了几种不同的代码,使用左连接或子查询,但没有一个起作用。这两个数量不能相加。 现在的结果是:

po_no  |inv_mast_uid|container_qty_received
1000019|12          |9700
1000118|2852        |320000
1000118|2852        |3250000

这是我的尝试之一。

SELECT a.inv_mast_uid
, b.qty_in_vessel as qty_in_vessel
, c.po_no
FROM po_line a
LEFT JOIN
po_hdr AS c ON a.po_no = c.po_no
LEFT JOIN 
(
SELECT vessel_receipts_line.po_line_uid, SUM(vessel_receipts_line.container_qty_received) AS qty_in_vessel
FROM vessel_receipts_line
WHERE vessel_receipts_line.row_status_flag = 702
GROUP BY
vessel_receipts_line.po_line_uid
) AS b
ON b.po_line_uid = a.po_line_uid
GROUP BY
a.inv_mast_uid, b.qty_in_vessel, c.po_no
ORDER BY c.po_no

请帮助!

1 个答案:

答案 0 :(得分:0)

po_line上加入vessel_receipts_linepo_line_uid,按po_noinv_mast_uid分组并求和container_qty_received

SELECT pl.po_no,
       pl.inv_mast_uid,
       vrl.row_status_flag,
       sum(vrl.container_qty_received) container_qty_received
       FROM po_line pl
            INNER JOIN vessel_receipts_line vrl
                       ON vrl.po_line_uid = pl.po_line_uid
       GROUP BY pl.po_no,
                pl.inv_mast_uid,
                vrl.row_status_flag;

db<>fiddle