[英]How to combine the results of two MySQL queries into one?
Suppose I have a table like this: 假设我有一个这样的表:
How can I count the number of data that occur at the day of 2018-09-07
for each person, and the number of data that occur at the month 2018-09
for each person? 如何计算每个人在
2018-09-07
当天发生的数据数量以及每个人在2018-09
月份发生的数据数量?
I mean I want to create a table like this: 我的意思是我想创建一个像这样的表:
I know that 我知道
SELECT
name,
COUNT(*) AS day_count_2018_09_07
FROM data_table
WHERE
arrive_time >= '2018-09-07 00:00:00'
AND
arrive_time <= '2018-09-07 23:59:59'
GROUP BY name;
can generate the number of data that occur at the day of 2018-09-07 for each person, and 可以生成每个人在2018年9月7日当天发生的数据数量,并且
SELECT
name,
COUNT(*) AS month_count_2018_09
FROM data_table
WHERE
arrive_time >= '2018-09-01 00:00:00'
AND
arrive_time <= '2018-09-30 23:59:59'
GROUP BY name;
can generate the number of data that occur at the month 2018-09 for each person. 可以生成每个人在2018-09月份发生的数据数量。
But I don't know how to combine the above two queries so that day_count_2018_09_07
and month_count_2018_09
columns can be created in one query. 但我不知道如何将上述两个查询结合,从而
day_count_2018_09_07
和month_count_2018_09
列可以在一个查询中创建。
Here's the SQL fiddle where you can directly get the data in my question. 这是SQL提琴 ,您可以在其中直接获取问题中的数据。
You can use conditional aggregation to get both results from the same query: 您可以使用条件聚合从同一查询中获得两个结果:
SELECT name,
SUM(CASE WHEN SUBSTR(DATE(arrive_time),1,7)='2018-09' THEN 1 ELSE 0 END) AS month_count_2018_09,
SUM(CASE WHEN DATE(arrive_time)='2018-09-07' THEN 1 ELSE 0 END) AS day_count_2018_09_07
FROM data_table
GROUP BY name
Output: 输出:
name month_count_2018_09 day_count_2018_09_07
Ben 3 0
Jane 1 1
John 3 2
Try to combine them like that: 尝试像这样合并它们:
Select DayCounter.name, DayCounter.day_count_2018_09_07, MonthCounter.month_count_2018_09
from
(SELECT
name,
COUNT(*) AS day_count_2018_09_07
FROM data_table
WHERE
arrive_time >= '2018-09-07 00:00:00'
AND
arrive_time <= '2018-09-07 23:59:59'
GROUP BY name) as DayCounter
Inner Join
(SELECT
name,
COUNT(*) AS month_count_2018_09
FROM data_table
WHERE
arrive_time >= '2018-09-01 00:00:00'
AND
arrive_time <= '2018-09-30 23:59:59'
GROUP BY name) as MonthCounter
On DayCounter.name = MonthCounter.name
What about something like this: 像这样的事情呢:
SELECT
name,
SUM(CASE WHEN (arrive_time BETWEEN '2018-09-07 00:00:00' AND '2018-09-07 23:59:59') THEN 1 ELSE 0 END) AS day_count_2018_09_07,
SUM(CASE WHEN (arrive_time BETWEEN '2018-09-01 00:00:00' AND '2018-09-30 23:59:59') THEN 1 ELSE 0 END) AS month_count_2018_09
FROM
data_table
GROUP BY
name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.