0

如何获取SUM两个表中的字段,我有两个表,我的表是laporanand laporan_pengeluaran

桌拉波兰

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

我的问题是,如何通过连接表和分组获得 SUM,关系是 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

谢谢。

4

2 回答 2

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第二个查询中没有。您需要在子查询中总结每个。第二个需要加入另一个表才能获取日期:

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;
于 2013-07-19T17:34:28.990 回答
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
于 2013-07-19T17:34:33.210 回答