我需要创建一个摘要报告。我有两个表,分别是产品和订单。 我要创建这个:
在两个表中:
产品
订单
我尝试查询:
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
每个月,但是当给定月份不存在产品类型时,我遇到问题。
任何人都有生成此类报告的解决方案吗?
答案 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