如何根据日期列将行转换为列?

时间:2015-09-07 11:31:11

标签: mysql sql database query-optimization

这是SQL小提琴

http://sqlfiddle.com/#!9/25542/2/0

我只想把我的数据作为

Sale_On    | Count Refunded | Count Sale | Count Cashback
-------------------------------------------------------
2015-09-07 |   1            |    5       |     1

我在MySQL中读到了“case-when”,但在这种情况下,我必须手动编写每个order_status。

我该怎么做?任何其他解决方案,而不是将行转换为列?

2 个答案:

答案 0 :(得分:3)

如果您愿意对状态进行硬编码,则可以对它们进行聚合:

SELECT   DATE(o.sale_on),
         SUM(od.order_status=1) AS Sales,
         SUM(od.order_status=2) AS Refunds,
         SUM(od.order_status=3) AS Cashbacks
FROM     orders o RIGHT JOIN order_detail od USING (order_id)
GROUP BY DATE(o.sale_on)

sqlfiddle上查看。

否则,您实际上需要使用master_order_status表上的查询动态生成类似的SQL,以生成选择列表中的相应列。

答案 1 :(得分:0)

或试试这个

select sale_on,
max(case when status='sale' then c end) as count_Sales,
max(case when status='Refunded' then c end) as count_Refunded,
max(case when status='CashBack' then c end) as count_CashBack
from
(
SELECT o.sale_on,od.order_status,COUNT(*) as c,mos.status FROM orders o
RIGHT JOIN order_detail od ON o.order_id = od.order_id
LEFT JOIN `master_order_status` mos ON mos.`status_id` = od.order_status
GROUP BY DATE(o.sale_on),od.order_status
  ) as t group by sale_on

SQL小提琴http://sqlfiddle.com/#!9/25542/13