要在没有行的情况下返回0

时间:2019-07-12 10:06:26

标签: sql

select 
    IMEI_ID, dev_status, nvl(count(1), 0) AS Count
from 
    device
where 
    IMEI_ID IN (284700, 250779, 320700, 339622, 323400)
    and Dev_status = 'ACTIVE'
group by 
    IMEI_ID,dev_status;

对于少数IMEI_ID,不返回任何行。我希望这些丢失的行的计数为零(0)。

谢谢

2 个答案:

答案 0 :(得分:1)

对于Oracle

with i(ime_id) as
( 
    SELECT 284700 FROM DUAL UNION ALL
    SELECT 250779 FROM DUAL UNION ALL
    SELECT 320700 FROM DUAL UNION ALL
    SELECT 339622 FROM DUAL UNION ALL
    SELECT 323400 FROM DUAL 
)
select i.IMEI_ID, d.dev_status, nvl(count(d.ime_id),0) AS Count
from i
left join device d on i.ime_id = d.IMEI_ID
   and d.Dev_status='ACTIVE'
group by i.IMEI_ID, d.dev_status;

答案 1 :(得分:0)

使用请求的IMEI_ID,然后在设备上的LEFT OUTER JOIN创建一个(临时)表:

SELECT          imei_ids.imei_id,
                device.dev_status,
                COUNT(device.dev_status)
FROM            imei_ids
LEFT OUTER JOIN device
             ON imei_ids.imei_id = device.imei_id
            AND device.dev_status = 'ACTIVE'
GROUP BY        imei_ids.imei_id,
                device.dev_status;