我有两张桌子,表#1 => tbl_notification_flow具有以下信息:
app_status
Booked
Notified
Missed
Defaulted
app_status是列名,表#2 => tbl_appointment具有以下信息:
id app_status
1 Booked
3 Missed
4 Missed
5 Missed
6 Missed
7 Booked
8 Booked
9 Booked
10 Booked
11 Booked
12 Booked
13 Booked
14 Booked
15 Booked
17 Booked
18 Booked
19 Booked
20 Defaulted
21 Notified
id和app_status是列,
我希望根据他们在表#2上出现的次数来计算所有app_status,
我尝试了以下查询:
SELECT COUNT(tbl_appointment.id)AS total_count, tbl_appointment.`app_status`
FROM tbl_appointment
WHERE (tbl_appointment.`app_status`) IN
(
SELECT tbl_notification_flow.`notification_type` AS app_status FROM tbl_notification_flow WHERE tbl_notification_flow.notification_type !='Other'
)
得到以下结果:
total_count app_status
19 Booked
请帮助您获得最佳查询以获得正确的结果。
答案 0 :(得分:0)
您应该按app_status
汇总数据。
以下是参考资料:
SELECT COUNT(tbl_appointment.id)AS total_count,tbl_appointment.`app_status`
FROM tbl_appointment
WHERE (tbl_appointment.`app_status`) IN
(
SELECT tbl_notification_flow.`notification_type` AS app_status
FROM tbl_notification_flow
WHERE tbl_notification_flow.notification_type !='Other'
)
GROUP BY tbl_appointment.`app_status`
答案 1 :(得分:0)
使用GROUP BY
计算每种通知类型,并利用LEFT JOIN
来说明tbl_appointment
中没有特定类型事件的情况,在这种情况下,您会获得0
1}}而不是结果集中缺少的行。
SELECT n.notification_type app_status, COUNT(a.id) count
FROM tbl_notification_flow n LEFT JOIN tbl_appointment a
ON n.notification_type = a.app_status
WHERE n.notification_type <> 'Other'
GROUP BY n.notification_type
输出:
+------------+-------------+ | app_status | total_count | +------------+-------------+ | Booked | 13 | | Defaulted | 1 | | Missed | 4 | | Notified | 1 | +------------+-------------+