【问题标题】:Query to combine two tables group by month查询按月组合两个表
【发布时间】:2021-10-14 07:23:56
【问题描述】:

我尝试通过 join 连接两个表并将它们分组以获取计数。但不幸的是,这两个表没有任何共同的加入价值(或者我误解了解决方案)。

select date_format(check_in.date,'%M') as Month, count(check_in.Id) as checkInCount 
from check_in 
group by month(check_in.date);
Month checkInCount
July 1
October 2

这是第一张桌子。

select date_format(reservation.date,'%M') as Month, count(reservation.id) as reserveCount 
from reservation
group by month(reservation.date);
Month reserveCount
July 3
October 5

这是第二张桌子。 我想在一张表中显示这两个表。

Month checkInCount reserveCount
July 1 3
October 2 5

感谢您尝试这个,如果这太简单了,我们很抱歉。

【问题讨论】:

  • 将这些查询作为 FROM 中的子查询,按月加入。

标签: mysql join


【解决方案1】:

您需要通过month 从您的两个子查询中加入结果。 此查询假定所有month(七月、八月、九月...)存在于您的子查询monthCheckInStatmonthCheckOutStat,即使计数为0

SELECT monthCheckInStat.Month, monthCheckInStat.checkInCount, monthCheckOutStat.reserveCount
FROM
(
    select date_format(check_in.date,'%M') as Month, count(check_in.Id) as checkInCount 
    from check_in 
    group by month(check_in.date)
) monthCheckInStat
INNER JOIN
(
    select date_format(reservation.date,'%M') as Month, count(reservation.id) as reserveCount 
    from reservation
    group by month(reservation.date)
) monthCheckOutStat
ON monthCheckInStat.Month = monthCheckOutStat.Month;

【讨论】:

  • 它工作了 90% 先生。但问题是这两个表通常只有几个月的结果。但我想要所有的月份。如果一张表对该月没有任何价值,则它必须为“0”。先生可以吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-17
  • 2019-05-06
  • 1970-01-01
  • 2013-05-20
  • 2018-11-18
相关资源
最近更新 更多