[英]php mysql sum amount of table2 and group by table one's field
i want to sum amount from sale table and want to group it by brand, can anyone help me to right query of php mysql. 我想从销售表中总结金额,并希望按品牌分组,任何人都可以帮我正确查询php mysql。
--- product ---
id pcode pname brand
1 123 Dalda 1
2 124 Habib 1
3 125 Sufi 2
4 126 Toyota 3
--- sale ---
id pcode pname amount
1 123 Dalda 1020
2 123 Dalda 1020
3 124 Habib 1030
4 124 Habib 1030
5 125 Sufi 1040
6 125 Sufi 1040
7 126 Toyota 1050
SELECT
p.pname,
IFNULL(SUM(amount), 0) AS TotalAmount
FROM product p
LEFT JOIN sale s ON p.pcode = s.pcode
GROUP BY p.pname;
This will give you: 这会给你:
| PNAME | TOTALAMOUNT |
------------------------
| Dalda | 2040 |
| Habib | 2060 |
| Sufi | 2080 |
| Toyota | 1050 |
Note that: There is no need to store the pname
in the second table Sale
. 请注意:无需将
pname
存储在第二个表Sale
。 Remove it since it is already stored in the first table Product
. 删除它,因为它已存储在第一个表
Product
。
select p.brand, sum(s.amount)
FROM product p
INNER JOIN sale s on s.pcode = p.pcode
GROUP BY p.brand
You will get only brands with an entry in sales table. 您将只获得在销售表中有条目的品牌。
if you want all the brands, even without an entry in sale table, then use a LEFT JOIN
and 如果您想要所有品牌,即使没有进入销售表,也可以使用
LEFT JOIN
和
COALESCE(SUM(amount, 0))
By the way, as pointed by Mahmoud Gamal, you don't need the pname in table Sale. 顺便说一句,正如Mahmoud Gamal所指出的,你不需要表Sale中的pname。 I wouldn't use pcode as "relation column" also, but use product id.
我也不会将pcode用作“关系列”,而是使用产品ID。 So you may remove pcode and pname and use a new column p_id, for example.
因此,您可以删除pcode和pname,并使用新列p_id。
select pr.pcode,pr.pname,pr.brand,sum(s.amount)
from product pr
left join sale s
on pr.pcode=s.pcode
group by pr.pcode,pr.pname,pr.brand
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.