如何将两个MySQL查询的结果合并为一个?

时间:2018-09-29 03:13:17

标签: mysql

假设我有一个这样的表:

enter image description here

我如何计算每个人在2018-09-07当天发生的数据数量,以及每个人在2018-09月份所发生的数据数量?

我的意思是我想创建一个这样的表:

enter image description here

我知道

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;

可以生成每个人在2018-09-07日发生的数据数量,并且

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;

可以生成每个人在2018-09月份发生的数据数量。

但是我不知道如何组合以上两个查询,以便可以在一个查询中创建day_count_2018_09_07month_count_2018_09列。

这里是SQL fiddle,您可以在其中直接获取我的问题中的数据。

3 个答案:

答案 0 :(得分:3)

您可以使用条件聚合从同一查询中获得两个结果:

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

输出:

name    month_count_2018_09     day_count_2018_09_07
Ben     3                       0
Jane    1                       1
John    3                       2

答案 1 :(得分:2)

尝试这样合并它们:

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

答案 2 :(得分:0)

那这样的事情呢?

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;