用 2 个聚合函数连接 3 个表

问题描述 投票:0回答:1

我有如下3张桌子:

工作、零件和切割日志

我正在尝试编写一个查询来检索以下内容:

客户名称、SUM_OF_PARTQUANTITY、SUM_OF_LOGQUANTITY

SUM_OF_PARTQUANTITY 列将是 PARTS 表中 PARTQUANTITY 的总和,其中 JOBID = JOBS.ID

SUM_OF_LOGQUANTITY 列将是 CUTLOG 表中 LOGQUANTITY 的总和,其中 PARTID = PARTS.PARTID

我已经厌倦了这个,它有效,但 SUM 的结果不正确:

SELECT J.JOBID, J.CUSTOMER_NAME, Sum(P.PARTQUANTITY), Sum(L.LOGQUANTITY)
    FROM JOBS J
    JOIN PARTS P 
        on J.JOBID = P.JOBID 
    FULL JOIN CUTLOG L
        on P.PARTID = L.PARTID
    Group by J.JOBID, J.CUSTOMER_NAME
    

以下是示例数据和示例结果。谢谢你

数据和结果示例

join sum aggregate
1个回答
0
投票

在应用合计总和之前,通过连接表格,您似乎获得了原本不希望获得的产品。先求和再加入就可以解决问题了:

SELECT   j.jobid, j.customer_name, 
         SUM(spq) AS sum_of_partquantity,
         SUM(slq) AS sum_of_logquantity
FROM     jobs j
JOIN     (SELECT   jobid, partid, SUM(partquantity) AS spq
          FROM     parts  
          GROUP BY jobid, partid) p ON p.jobid = j.jobid
JOIN     (SELECT   partid, SUM(logquantity) AS slq
          FROM     cutlog
          GROUP BY partid) c ON c.partid = p.partid
GROUP BY j.jobid, j.customer_name
ORDER BY j.jobid

DBFiddle 演示

© www.soinside.com 2019 - 2024. All rights reserved.