创建具有总计的

时间:2019-02-28 21:02:29

标签: php mysql sql summary totals

我需要创建一个摘要报告。我有两个表,分别是产品和订单。 我要创建这个:

Results

在两个表中:

产品

Products

订单

Orders

我尝试查询:

 SELECT round(SUM(price),2),0)
FROM products, orders
WHERE products.id_products = orders.id_products AND MONTH(orders.date) = 1 AND YEAR(orders.date) = '2019'
GROUP BY products.type

每个月,但是当给定月份不存在产品类型时,我遇到问题。

任何人都有生成此类报告的解决方案吗?

1 个答案:

答案 0 :(得分:1)

使用条件聚合

SELECT
    p.type_product,
    SUM(CASE WHEN YEAR(o.date) = 2019 AND MONTH(o.date) = 1 THEN o.price ELSE 0 END) January,
    SUM(CASE WHEN YEAR(o.date) = 2019 AND MONTH(o.date) = 2 THEN o.price ELSE 0 END) February
FROM 
    products p
    INNER JOIN orders o ON oid_product. = p.id_product
GROUP BY p.type_product