2013-07-19 91 views
0

如何在兩個表中獲得SUM字段,我有兩個表,我的表是laporanlaporan_pengeluaran如何在兩個表中總結字段並按日期分組

表laporan

id shell date_created 
9 12000 2013-07-01 
10 24000 2013-07-01 
11 5500  2013-07-02 

表laporan_pengeluaran

id laporan_id harga 
1 9   15000 
2 9   29000 
3 10   7500 
4 10   5000 

我的問題,如何獲得與天連接表和組之和,關係laporan.id與laporan_pengeluaran .laporan_id。所以我希望得到如下結果:

c_date_created c_shell c_harga 
2013-07-01  36000 44000 
2013-07-02  5500  12500 

現在我的查詢是在下面,而不是更迭:-(,導致c_shell無序

SELECT 
    l.date_created as c_date_created 
    SUM(l.shell) as c_shell, 
    SUM(lp.harga) as c_harga, 
    l.* 
    FROM laporan l 
    LEFT JOIN laporan_pengeluaran lp ON l.id=lp.laporan_id 
    WHERE l.date_created BETWEEN '2013-07-01' AND '2013-07-05' 
    GROUP BY l.date_created 
    ORDER BY l.date_created ASC 

感謝

+0

我認爲您的示例結果對於示例表格不正確。 – Barmar

+0

如果'laporan_id'是9,10,11,11,你的結果是正確的。 – Barmar

回答

1

您需要組第二表中的子查詢前加入,因爲它在不同的列進行分組。

SELECT l.date_created as c_date_created, 
SUM(l.shell) as c_shell, 
SUM(lp.c_harga) as c_harga, 
l.* 
FROM laporan l 
LEFT JOIN (SELECT laporan_id, 
        SUM(harga) as c_harga 
      FROM laporan_pengeluaran 
      GROUP BY laporan_id) as lp 
ON l.id = lp.laporan_id 
WHERE l.date_created BETWEEN '2013-07-01' AND '2013-07-05' 
GROUP BY l.date_created 
ORDER BY l.date_created ASC 
+0

結果c_harga仍然是錯誤的先生,c_harga不是SUM :-( –

+0

修復它。在外部查詢中需要另一個SUM。 – Barmar

+0

您是搖滾先生,謝謝..問題已解決.. Yeaahhhh !!! –

1

的問題。你面對的是一個表中的多行與第二行中的多行匹配 - 所以你在每個日期都得到一個交叉產品

解決方案是在進行連接之前進行聚合:

SELECT l.date_created as c_date_created 
     l.c_shell, 
     SUM(lp.harga) as c_harga, 
FROM (select l.date_created, l.shell as c_shell 
     from laporan l 
     WHERE l.date_created BETWEEN '2013-07-01' AND '2013-07-05' 
     group by l.date_created 
    ) l LEFT JOIN 
    laporan_pengeluaran lp 
    ON l.id=lp.laporan_id 
GROUP BY l.date_created 
ORDER BY l.date_created ASC; 

編輯:

我明白了。 join在ID上,而不是在日期上。上述甚至不起作用,因爲id不在第二個查詢中。你需要在子查詢中總結每一個。第二個需要爲了加入再換另一表來獲得日期:

SELECT l.date_created as c_date_created 
     l.c_shell, 
     lp.c_harga, 
FROM (select l.date_created, l.shell as c_shell 
     from laporan l 
     WHERE l.date_created BETWEEN '2013-07-01' AND '2013-07-05' 
     group by l.date_created 
    ) l LEFT JOIN 
    (select l.date_created, sum(lp.harga) as c_harga 
     from laporan l join 
      laporan_pengeluaran lp 
      on l.id=lp.laporan_id 
     group by l.date_created 
    ) lp 
    ON l.date_created = lp.date_created 
ORDER BY l.date_created ASC; 
+0

你好,先生,問題與Barmar先生一起解決。感謝您的幫助,我給你大拇指。再次感謝。 –

相關問題