MySQL查询与2个日期字段

时间:2018-08-22 13:36:28

标签: mysql sql

id course_id user_id state created_date        approved_date       finished finished_date       result total percentage
14        12       8     1 2018-08-19 19:58:22 NULL               0 0000-00-00 00:00:00 NULL   NULL           0
13        11       8     1 2018-08-19 19:58:14 NULL               0 0000-00-00 00:00:00 NULL   NULL           0
12        10       8     1 2018-08-19 19:58:07 NULL               1 2018-08-20 00:00:00    2      4           0
11         9       8     1 2018-08-18 19:57:58 2018-08-21 18:07:19        0 0000-00-00 00:00:00 NULL   NULL           

0

我有一张这样的桌子。我想知道每天创建(created_date)和完成(finished_date)几门课程(course_id)。 例子

+------------+----------+---------+
| date       | created  | finished|
+------------+----------+---------+
| 2018-08-18 |     1    |     0   |
| 2018-08-19 |     3    |     0   |
| 2018-08-20 |     0    |     1   |
+------------+----------+---------+

我可以通过一个查询获得此结果吗?

2 个答案:

答案 0 :(得分:1)

You can use the following query:

SELECT `date`, SUM(created) AS created, SUM(finished) AS finished FROM (
    SELECT DATE(created_date) AS `date`, 0 AS finished, COUNT(*) AS created
    FROM test 
    GROUP BY DATE(created_date)
    UNION ALL
    SELECT DATE(finished_date), COUNT(*), 0 
    FROM test
    GROUP BY DATE(finished_date)
)x WHERE STR_TO_DATE(`date`, '%Y-%m-%d') IS NOT NULL
GROUP BY `date`
ORDER BY `date`

demo: https://www.db-fiddle.com/f/tkym4G9wGvkTCMesEuNa8v/0

答案 1 :(得分:1)

You can write something like this to get the desired output

select a.date,sum(a.CoursesCreated) as Created,sum(a.CoursesFinished) as finished from
(Select date(created_date) as date,count(course_id) as CoursesCreated, 0 as CoursesFinished from table /*where condition(if required)*/
group by date(created_date) 
    union all
    select date(finished_date) as date,0 as CoursesCreated, count(course_id) as CoursesFinished from table
  where finished_date !='0000-00-00 00:00:00'
 group by date(finished_date) ) a 
group by a.date

PS- You can add where condition in CoursesCreated case also to exclude counting if created_date is something like '0000-00-00 00:00:00'