0

如何SUM使用查询JOIN表进行查询,我有两个表,我的表是laporanlaporan_pengeluaran

桌拉波兰

id  name    shell
9   loli    12000
10  ardi    24000
11  dian    5500

表 laporan_pengeluaran

id  laporan_id  harga
1   9           15000
2   9           29000
3   10          7500
4   10          5000
5   11          3000
6   11          3000

我的问题,如何通过连接表获得 SUM,在表 laporan 中按 id/name 分组,所以我想得到如下结果:

id  name    shell   harga
9   loli    12000   44000
10  ardi    24000   12500
11  dian    5500    6000

谢谢。

4

4 回答 4

5

您可以连接这两个表,然后sum(harga)得到结果。如果你知道你的表中总会有laporan值,laporan_pengeluaran那么你可以使用INNER JOIN

select l.id,
  l.name,
  l.shell,
  sum(lp.harga) harga
from laporan l
inner join laporan_pengeluaran lp
  on l.id = lp.laporan_id
group by l.id, l.name, l.shell

请参阅带有演示的 SQL Fiddle

如果表中可能缺少laporan值,请laporan_pengeluaran使用LEFT JOIN

select l.id,
  l.name,
  l.shell,
  sum(lp.harga) harga
from laporan l
left join laporan_pengeluaran lp
  on l.id = lp.laporan_id
group by l.id, l.name, l.shell

请参阅带有演示的 SQL Fiddle

结果是:

| ID | NAME | SHELL | HARGA |
-----------------------------
|  9 | loli | 12000 | 44000 |
| 10 | ardi | 24000 | 12500 |
| 11 | dian |  5500 |  6000 |
于 2013-01-04T19:05:52.130 回答
0
SELECT
  laporan.id AS id,
  laporan.name AS name,
  laporan.shell AS shell,
  IFNULL(SUM(laporan_pengeluaran.harga),0) AS harga
FROM laporan
LEFT JOIN laporan_pengeluaran ON laporan.id=laporan_pengeluaran.laporan_id
于 2013-01-04T19:06:44.373 回答
0

尝试这个:

SELECT l.id, l.name, l.shell, SUM(lp.harga) harga 
FROM laporan l 
LEFT JOIN laporan_pengeluaran lp ON l.id = lp.laporan_id 
GROUP BY l.id; 

检查这个SQL FIDDLE 演示

输出:

| ID | NAME | SHELL | HARGA |
-----------------------------
|  9 | loli | 12000 | 44000 |
| 10 | ardi | 24000 | 12500 |
| 11 | dian |  5500 |  6000 |
于 2013-03-02T07:05:17.893 回答
0

试试这个查询

SELECT
    l.id,
    l.name,
    IFNULL(lp.TCount,0) as Total
FROM laporan as l   
LEFT JOIN (
            SELECT 
                laporan_id,
                SUM(harga) as TCount
            FROM    laporan_pengeluaran
            GROUP BY laporan_id
            ) as lp ON lp.laporan_id = l.id
于 2013-01-04T19:08:00.890 回答