gpt4 book ai didi

mySQL 从两个连接表中选择子查询中的数据总和

转载 作者:行者123 更新时间:2023-11-29 07:01:32 25 4
gpt4 key购买 nike

我有一个像这样的表“schLoc”

------------------------
| id | ... | ... | ... |
------------------------
| 1 | ... | ... | ... |
| 2 | ... | ... | ... |
| 3 | ... | ... | ... |
| 4 | ... | ... | ... |
| 5 | ... | ... | ... |
| .. | ... | ... | ... |
------------------------

还有另一个像这样的“schLocDett”表,其中 schLoc.id=schLocDett.idDoc

-------------------------------
| idDoc | qta | ... | merce |
-------------------------------
| 1 | 1 | ... | fattLoc |
| 1 | 1 | ... | fattSrv |
| 2 | 3 | ... | fattLoc |
| 2 | 2 | ... | notcSrv |
| 2 | 2 | ... | fattSrv |
| 3 | 5 | ... | fattSrv |
| 3 | 3 | ... | notcSrv |
| 3 | 3 | ... | fattLoc |
| 3 | 7 | ... | fattLoc |
| 4 | 5 | ... | notcSrv |
| 4 | 4 | ... | fattSrv |
| 4 | 1 | ... | fattSrv |
| 5 | 1 | ... | notcSrv |
| ... | ... | ... | ....... |
-------------------------------

我想要完整的 schLoc 列表以及每个 id 关联的 qta 总和,但仅限于 Merce=fattLoc。如果不存在,总和将为 0。这就是我期望的结果

---------------------------
| id | sumQta | ... | ... |
------------------------
| 1 | 1 | ... | ... |
| 2 | 3 | ... | ... |
| 3 | 10 | ... | ... |
| 4 | 0 | ... | ... |
| 5 | 0 | ... | ... |
| .. | ... | ... | ... |
---------------------------

我尝试这样做:

SELECT TOT.sumQta, TAB.*, 
FROM schLoc AS TAB, schLocDett AS DETT,
(SELECT idDoc, SUM(qta) AS sumQta
FROM schLocDett
WHERE merce='fattLoc'
GROUP BY idDoc) AS TOT
WHERE TAB.id>0
AND TAB.id=DETT.idDoc
AND TAB.id=TOT.idDoc

但未获取 ID 4 和 5

欢迎任何建议

最佳答案

SELECT TAB.*, COALESCE(TOT.sumQta, 0) AS sumQta
FROM schLoc TAB
LEFT JOIN
(
SELECT idDoc, SUM(qta) AS sumQta
FROM schLocDett
WHERE merce = 'fattLoc'
GROUP BY idDoc
) TOT
ON TAB.id = TOT.idDoc

输出:

enter image description here

此处演示:

Rextester

关于mySQL 从两个连接表中选择子查询中的数据总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43249450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com