Reputation: 13573
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?
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
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.
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.
Here's the SQL fiddle where you can directly get the data in my question.
Upvotes: 2
Views: 51
Reputation: 17190
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;
Upvotes: 0
Reputation: 147166
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
Upvotes: 3
Reputation: 3506
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
Upvotes: 2