MySQL - Count和GroupBy

时间:2017-12-17 16:30:52

标签: mysql sql select

我有这个结构:

id|  date_1  |  date_2
---------------------
01|2017-01-01|2017-02-22
02|2017-01-02|2017-03-25
03|2017-02-10|2017-03-20
04|2017-03-11|2017-04-10
05|2017-03-15|2017-05-01
06|2017-03-20|2017-05-20

我需要这样的结果:

Month  |Count(date_1)|Count(date_2)
---------------------------------
2017-01| 2           | 0
2017-02| 1           | 1
2017-03| 3           | 2
2017-04| 0           | 1
2017-05| 0           | 2

现在,我使用此查询(它仅适用于一个日期):

SELECT CONCAT(YEAR(date_1), '-', DATE_FORMAT(date_1,'%m')) AS month,
COUNT(*) AS items
FROM table
GROUP BY YEAR(date_1), MONTH(date_1)
ORDER BY date_1 DESC

3 个答案:

答案 0 :(得分:1)

您可以将所有日期值合并,然后对它们进行分组和计数:

SELECT   DATE_FORMAT(d, '%y-%m'), COUNT(*)
FROM     (SELECT date_1 AS d FROM mytable 
          UNION ALL
          SELECT date_2 FROM mytable) t
GROUP BY DATE_FORMAT(d, '%y-%m')
ORDER BY d DESC

答案 1 :(得分:1)

使用子查询获取date_1和date_2在两个不同字段中的计数:

{{1}}

答案 2 :(得分:1)

考虑使用SELECT

后面的子查询
SELECT   distinct DATE_FORMAT(t.d, '%y-%m'),
     (
        SELECT count(*) 
        FROM your_table as dd 
        where DATE_FORMAT(dd.date_1, '%y-%m') = DATE_FORMAT(t.d, '%y-%m')
     ) as count_date_1,
     (
        SELECT count(*) 
        FROM your_table as dd 
        WHERE DATE_FORMAT(dd.date_2, '%y-%m') = DATE_FORMAT(t.d, '%y-%m')
     ) as count_date_2
FROM     
(
  SELECT date_1 AS d FROM your_table 
      UNION ALL
  SELECT date_2 as d FROM your_table
) as t

dbfiddle demo