Table:patient
patient_id varchar(50)
name varchar(50)
email_id varchar(50)
country_id varchar(50)
mobile_no varchar(20)
Table:Booking
booking_id varchar(50)
patient_id varchar(50)
booking_date date
booking_status varchar(20) ---- contains the data: Booked, Cancel
booking_type varchar(20)
booking_id patient_id booking_date booking_status booking_type
2455 111 21-12-2015 Booked Via mobile
2424 123 21-12-2015 Cancel Via web
2455 111 21-12-2015 Cancel Via Web
2455 111 21-12-2015 Cancel Via mobile
患者将预约并取消与医生的预约。这些将存储在这些表中。预订状态包含预订和取消详细信息的记录。
我们希望计算每位患者的预订数量和超过3个取消的详细信息。
Expected output:
Name Email_id Mobile no Appointment booked cancelled
san san@gmail.com 235846 2 7
gow asas@sfsvs 48645151 1 4
abd ddscz@fsf 489644 4 5
答案 0 :(得分:2)
这称为条件计数。您可以将count()和sum()与条件语句一起用作参数以获得预期输出。我正在为下面的sum()版本提供一个示例:
select p.patient_id,
p.email_id,
p.mobile_no,
sum(if(b.booking_status='Booked',1,0)) as AppointmentBooked,
sum(if(b.booking_status='Cancel',1,0)) as AppointmentCanceled
from patient p left join booking b on p.patient_id=b.patient_id
group by p.patient_id, p.email_id, p.mobile_no
having AppointmentCanceled>3
答案 1 :(得分:0)
以下查询也有效。
select p.name,p.email_id,p.mobileno,
SUM(CASE WHEN b.booking_status='Booked' THEN 1 ELSE 0 END) AS bookedcount,
SUM(CASE WHEN b.booking_status='Cancel' THEN 1 ELSE 0 END) AS cancelcount
from patient p left join booking b
on p.patient_id=b.patient_id group by p.patient_id,p.email_id,p.mobileno
having cancelcount>3;