我有一个这样的桌子;
deviceId, status, time
状态列可能仅active, idle, alarm
。我想查找具有所有状态值的所有deviceIds。
因此,如果一台设备在该表的状态列中具有active, idle and alarm
值,我希望它是ID。
我该怎么做?
答案 0 :(得分:1)
您可以使用group by
和having
。如果您知道三个值,请执行以下操作:
select deviceId
from t
group by deviceId
having count(distinct status) = 3;
如果您不知道该列中的值数,请使用子查询来计算它们:
select deviceId
from t
group by deviceId
having count(distinct status) = (select count(distinct status) from t);
如果要特别使用这三个,请添加一个where
子句:
select deviceId
from t
where status in ('active', 'idle', 'alarm')
group by deviceId
having count(distinct status) = 3;