mysql创建具有2个不同选择的表

busg9geu  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(210)
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\ u name,number of returned devices和number of not returned devices。基本上,我需要的是合并这两个选择在一个表中,但我卡住了。

3phpmpom

3phpmpom1#

只需使用条件聚合:

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;

相关问题