如何查找具有特定列的所有值的设备?

时间:2019-09-18 22:50:52

标签: sql

我有一个这样的桌子;

deviceId, status, time

状态列可能仅active, idle, alarm。我想查找具有所有状态值的所有deviceIds。

因此,如果一台设备在该表的状态列中具有active, idle and alarm值,我希望它是ID。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用group byhaving。如果您知道三个值,请执行以下操作:

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;