如何在两个表中获取SUM
个字段,我有两个表,我的表是laporan
和laporan_pengeluaran
。
table laporan
id shell date_created
9 12000 2013-07-01
10 24000 2013-07-01
11 5500 2013-07-02
table laporan_pengeluaran
id laporan_id harga
1 9 15000
2 9 29000
3 10 7500
4 10 5000
我的问题是,如何按日获得连接表和组的SUM,并且与laporan_pengeluaran.laporan_id的关系是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 :(得分: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;
答案 1 :(得分: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