mysql - MySQL SUM with 3 relation tables
问题描述
I have 3 tables with the following columns, they are:
- THead - HeadID(PK), padcode, OKqty, TotNGqty
- TDetail - HeadID(FK), process, name, Subcode
- TSubDetail - Subcode(FK), NGcode, NGqty
The relations of the 3 tables are like this: THead - TDetail - TSubDetail.
I hope following images can show them clearly.
This is my MySQL Query:
SELECT
THead.padcode,
SUM(THead.okqty) AS OK,
SUM(THead.TotNGqty) AS TOTALNG,
SUM(If(TSubDetail.NGCode = 'L3', NGqty, 0)) AS L3
FROM(THead JOIN TDetail ON THead.HeadID = TDetail.HeadID)
JOIN TSubDetail ON TDetail.Subcode=TSubDetail.Subcode
GROUP BY padcode
I want to sum the OK Qty and TotNGqty without adding the same values from the same TSubDetail.Subcode. I have tried DISTINCT, but that was not a solution.
From the image you can see from the yellow highlight sample:
For Padcode = 'KVBS-B'
I want to get the OK Qty = 2845 and the Sum NG from Table Head = 705.
But from the query above, i got the wrong result, OK = 3245 and NG = 905.
I know that the same values from the same TSubDetail.Subcode was added multiple times. But what is the correct query so i can get the true result?
I hope someone can help me and explain what is the correct query. Thanks in advance for helping me.
解决方案
您正在显示数据的子集,因此很难明确回答,但您的 GROUP BY 子句仅包含“padcode”列,而不包含 HeadID 列。
我假设在整个表格中,您有多个 HeadID 具有相同 padcode (KVBS-B) 的记录,而不仅仅是黄色显示的记录。结果它们也被求和了,但是你看不到是哪一个,因为 GROUP BY 太笼统了。
推荐阅读
- git - 如何将提交压缩到最后一次提交?- 订单问题
- php - 无法在 WordPress 主题编辑器中编辑文件
- powershell - 过滤名称:Get-WmiObject Win32_NetworkAdapter
- javascript - 在电话输入字段中只允许数字和一个 (+) 唱歌
- web - 对 MongoDB 进行搜索查询
- google-chrome - 如何在 chrome 中查找 toast 消息的元素
- spring-boot - 如何修复 401 - 未经授权 - 通过邮递员测试使用 google oauth2 保护的 Spring Rest API 时 - DB 中的角色
- sql - 如何在 azure Sql 中传递和处理字符串数组
- python - 通过添加数字使数组连续子序列
- apache-spark - 我们如何在 pyspark 中使用带有 dataframe API 而不是 SQL 的窗口函数(例如以 dense_rank 为例)?