我有两个表Order和Product。
要求是按季度列支表的收入
ProductId Q1 Q2 Q3 Q4
P1 30240 0 0 0
我很困惑,每季度保持列数。任何帮助表示赞赏。请查看图片以查看清晰
答案 0 :(得分:1)
Year()
函数按订单年份对数据进行了分组。Sum()
和If()
之类的条件聚合函数基于特定Quarter()
的分组来对特定行求和。Left join
表到Product
表执行Order
,因为可能很少Product
表中的产品,而Order
表中根本没有相应的条目。Order
在MySQL中是Reserved keyword。您应该将表名更改为其他名称。如果您不想这样做,可以在其周围使用反引号(`)。而且,使用Aliasing是个好习惯。尝试以下查询(在MySQL中):
SELECT YEAR(o.order_date) AS order_year,
p.ProductId,
SUM(IF(QUARTER(o.OrderDate) = 1, o.Quantity*p.Cost, 0)) AS Q1,
SUM(IF(QUARTER(o.OrderDate) = 2, o.Quantity*p.Cost, 0)) AS Q2,
SUM(IF(QUARTER(o.OrderDate) = 3, o.Quantity*p.Cost, 0)) AS Q3,
SUM(IF(QUARTER(o.OrderDate) = 4, o.Quantity*p.Cost, 0)) AS Q4
FROM Product AS p
LEFT JOIN `Order` AS o ON o.ProductId = p.ProductId
GROUP BY order_year, p.ProductId
Left Join
更改为Inner Join
。在这种情况下,请尝试以下操作(在MySQL中):
SELECT YEAR(o.order_date) AS order_year,
p.ProductId,
SUM(IF(QUARTER(o.OrderDate) = 1, o.Quantity*p.Cost, 0)) AS Q1,
SUM(IF(QUARTER(o.OrderDate) = 2, o.Quantity*p.Cost, 0)) AS Q2,
SUM(IF(QUARTER(o.OrderDate) = 3, o.Quantity*p.Cost, 0)) AS Q3,
SUM(IF(QUARTER(o.OrderDate) = 4, o.Quantity*p.Cost, 0)) AS Q4
FROM `Order` AS o
INNER JOIN Product AS p ON o.ProductId = p.ProductId
GROUP BY order_year, p.ProductId