MySQL日期范围多列计数和分组选择语句

时间:2016-02-06 17:18:48

标签: mysql sql date

我有一个问题,我一直在研究,但我似乎无法理解它。这里的其他答案适用于计算具有特定日期范围的金额,然后按日期分组以获得计数。但是,我需要计算两列并按日期分组。

例如,这里是我试图开始工作的查询:

(SELECT COUNT(*) arrived, DATE(arrived) date, 'arrived' AS source
FROM products 
WHERE arrived BETWEEN '2016-01-01' AND '2016-01-31'
GROUP BY DATE(date)
ORDER BY date ASC)

UNION ALL 

(SELECT COUNT(*) released, DATE(released) date, 'released' AS source
FROM products 
WHERE released BETWEEN '2016-01-01' AND '2016-01-31'
GROUP BY DATE(date)
ORDER BY date ASC)

然而,这会返回以下内容:

arrived  date       source
3        2016-01-12  arrived
2        2016-01-28  arrived
1        2016-01-29  arrived
1        2016-01-05  released

我要求的是这样的:

date           arrived   released   
2016-01-05     0         1
2016-01-12     3         0
2016-01-28     2         0
2016-01-29     1         0

有什么建议吗?谢谢。

1 个答案:

答案 0 :(得分:3)

您可以将条件聚合应用于UNION ALL操作获得的派生表格,以便'到达'和'发布'日期:

SELECT `date`, 
       COUNT(CASE WHEN type = 'arrived' THEN 1 END) AS arrived,
       COUNT(CASE WHEN type = 'released' THEN 1 END) AS released
FROM (
  SELECT arrived AS `date`, 'arrived' as type
  FROM products
  WHERE arrived BETWEEN '2016-01-01' AND '2016-01-31'

  UNION ALL

  SELECT released AS `date`, 'released' as type
  FROM products
  WHERE released BETWEEN '2016-01-01' AND '2016-01-31') AS t
GROUP BY `date`  

Demo here