SELECT COUNT(*) as not_returned_devices, contact_email FROM device_rent WHERE rent_end IS NULL GROUP BY contact_email;
SELECT COUNT(*) as returned_devices, contact_email FROM device_rent WHERE rent_end IS NOT NULL GROUP BY contact_email;
我需要的是创建一个包含3列的表:contact_name,返回的设备数和未返回的设备数。基本上,我需要的是在一个表中合并这两个选项,但我卡住了。
答案 0 :(得分:0)
只需使用条件聚合:
SELECT contact_email, SUM(rent_end IS NULL) as not_returned_devices,
SUM(rent_end IS NOT NULL) as returned_devices
FROM device_rent
GROUP BY contact_email;
请注意,这使用了一个MySQL快捷方式,其中布尔表达式被视为“1”表示true,“0”表示false。这是一种方便,并且可以避免编写case
语句。那看起来像是:
SELECT contact_email,
SUM(CASE WHEN rent_end IS NULL THEN 1 ELSE 0
END) as not_returned_devices,
COUNT(rent_end) as returned_devices
FROM device_rent
GROUP BY contact_email;