[英]Query to combine two tables group by month
我試圖通過 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);
月 | 簽入計數 |
---|---|
七月 | 1 |
十月 | 2 |
這是第一張桌子。
select date_format(reservation.date,'%M') as Month, count(reservation.id) as reserveCount
from reservation
group by month(reservation.date);
月 | 保留計數 |
---|---|
七月 | 3 |
十月 | 5 |
這是第二張桌子。 我想在一張表中顯示這兩個表。
月 | 簽入計數 | 保留計數 |
---|---|---|
七月 | 1 | 3 |
十月 | 2 | 5 |
感謝您嘗試此操作,如果這太簡單了,我們深表歉意。
您需要month
從兩個子查詢中加入結果。 此查詢假設您的子查詢中存在的所有month
(七月、八月、九月...) monthCheckInStat
、 monthCheckOutStat
,即使計數為 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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.