我的查询有问题,也许你可以帮助我。
我有这个数据,请检查
- Trans_lhphd (a) http://sqlfiddle.com/#!9/e1cef6/2
- Trans_lhpdthp (b) http://sqlfiddle.com/#!9/3d528e/1
这是我的查询:
SELECT
SUM(
IF (a.IdShift = '1', a.Planning, 0)
) AS Shift1,
SUM(
IF (a.IdShift = '2', a.Planning, 0)
) AS Shift2,
SUM(
IF (a.IdShift = '3', a.Planning, 0)
) AS Shift3,
SUM(a.Planning) AS total,
SUM(
IF (
b.IdShift = '1',
b.QtyProduksi,
0
)
) AS Shift1a,
SUM(
IF (
b.IdShift = '2',
b.QtyProduksi,
0
)
) AS Shift2a,
SUM(
IF (
b.IdShift = '3',
b.QtyProduksi,
0
)
) AS Shift3a
FROM
trans_lhphd a INNER JOIN trans_lhpdthp b ON
b.IdBukti= a.IdBukti
WHERE
a.DivisiId = 'DI070' AND
b.HasilProduksi = 'Good' AND
a.Tanggal BETWEEN '2017-10-01' AND
'2017-10-16'
GROUP BY
a.Tanggal
根据我的查询,结果是这样的:
| Shift1|Shift2|Shift3|total|Shift1a|Shift2a|Shift3a|
|-------|------|------|-----|-------|------ |-------|
| 4000 | 1200 |1210 |6410 |310 |450 |120 |
| 1000 | 0 |0 |1000 |500 |0 |0 |
我想要的结果一定是
| Shift1|Shift2|Shift3|total|Shift1a|Shift2a|Shift3a|
|-------|------|------|-----|-------|------ |-------|
| 2000 | 1200 |1210 |4410 |310 |450 |120 |
| 1000 | 0 |0 |1000 |500 |0 |0 |
字段 Shift1 错误,因为表 trans_lhpdthp 中有多于一行。
也许你可以帮忙修复它
最佳答案
在加入之前,您需要使用嵌套查询聚合trans_lhpdthp
:
替换:
FROM
trans_lhphd a INNER JOIN trans_lhpdthp b ON
b.IdBukti= a.IdBukti
作者:
FROM
trans_lhphd a INNER JOIN (
select
IdBukti,HasilProduksi,Tanggal,
sum(QtyProduksi) as QtyProduksi
from trans_lhpdthp
group by IdBukti,HasilProduksi,Tanggal) b ON
b.IdBukti= a.IdBukti
关于mysql - 使用内部联接在我的查询中出现多个重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47011751/