mysql - 使用内部联接在我的查询中出现多个重复

标签 mysql

我的查询有问题,也许你可以帮助我。

我有这个数据,请检查

  1. Trans_lhphd (a) http://sqlfiddle.com/#!9/e1cef6/2
  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/

相关文章:

mysql子查询理解

php - laravel 检索值与数据透视表匹配的所有用户

mysql - 为什么在另一个数据库中执行相同的查询时不使用索引?

c# - 如何找到导致 EntityCommandExecutionException 出现的原因

MySQL 查询一个简单的表

MySQL 使用文件导入命令行创建数据库(如果不存在)

php - 安装时 WordPress WSOD

javascript - 从动态选择框构造 mySQL 查询

Mysql 组 根据关系按类似产品(如果有)

php - 在类里面使用 PDO 与 php 和 mysql