MySQL查询显示输出的组合

时间:2016-06-19 06:55:39

标签: mysql

我必须编写一个mysql查询来查找特定日期的总销售额。我能够找到它,但无法显示综合结果。

表格如下:

Date, Order_id, Product_id, Quantity
'01-JUL-11',O1,P1,5
'01-JUL-11',O2,P2,2
'01-JUL-11',O3,P3,10
'01-JUL-11',O4,P1,10
'02-JUL-11',O5,P3,5
'02-JUL-11',O6,P4,6
'02-JUL-11',O7,P1,2
'02-JUL-11',O8,P5,1
'02-JUL-11',O9,P6,2
'02-JUL-11',O10,P2,4

期望的输出:

Product_id Total Sales on Day '02-JUL-11' Total Sales on Day '02-JUL-11'
P1 15 2
P2 2 4
P3 10 5
P4 0 6
P5 0 1
P6 0 2

我试过的是:

Select distinct product_id
from orders;

输出:

P1
P2
P3
P4
P5
P6

Select product_id, sum(quantity) from orders
where order_day = '11-07-01'
group by product_id

输出:

P1 15
P2 2
P3 10


Select product_id, sum(quantity) from orders
where order_day = '11-07-02'
group by product_id

输出:

P1 2
P2 4
P3 5
P4 6
P5 1
P6 2

这给了我想要的结果,但我想以某种方式组合列。

对我有用的查询:(但是将0设为null)

Select X.product_id, X.s, Y.t from 
(SELECT A.product_id as product_id, B.s as s FROM 
(Select distinct product_id
from orders) A
LEFT JOIN
(Select product_id, sum(quantity) as s from orders
where order_day = '11-07-01'
group by product_id) B
ON A.product_id = B.product_id) X
Left join
(Select product_id, sum(quantity) as t from orders
where order_day = '11-07-02'
group by product_id) Y
on X.product_id = Y.product_id;

2 个答案:

答案 0 :(得分:2)

如果您只需要在报告中汇总两天,那么简单(非动态)透视查询应该可以解决问题:

SELECT product_id,
    SUM(CASE WHEN order_day = '11-07-01' THEN quantity ELSE 0 END) AS `Total Sales on Day '01-JUL-11'`,
    SUM(CASE WHEN order_day = '11-07-02' THEN quantity ELSE 0 END) AS `Total Sales on Day '02-JUL-11'`
FROM orders
WHERE order_day = '11-07-01' OR order_day = '11-07-02'
GROUP BY product_id

答案 1 :(得分:1)

条件聚合是要走的路。但是你应该学会使用正确的日期格式。 ISO / ANSI标准是YYYY-MM-DD或YYYYMMDD:

Select product_id,
      sum(case when order_day = '2011-07-01' then quantity else 0 end) as q_20110701,     
      sum(case when order_day = '2011-07-02' then quantity else 0 end) as q_20110702
from orders o
where order_day in ('2011-07-01', '2011-07-02')
group by product_id;

另一种选择,如果您每天可以使用不同的行,则为:

Select product_id, order_day, sum(quantity)
from orders
where order_day in ('2011-07-01', '2011-07-02')
group by product_id, order_day,