使用内部联接

时间:2017-10-30 09:25:38

标签: mysql

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

我有这些数据,请检查

  1. Trans_lhphd(a) http://sqlfiddle.com/#!9/e1cef6/2
  2. Trans_lhpdthp(b) http://sqlfiddle.com/#!9/3d528e/1
  3. 这是我的疑问:

    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中有多行。

    也许你可以帮忙解决问题

1 个答案:

答案 0 :(得分:0)

在加入之前,您需要使用嵌套查询来聚合trans_lhpdthp

替换:

FROM
    trans_lhphd a INNER JOIN trans_lhpdthp b ON
        b.IdBukti= a.IdBukti

by:

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