如何从SQL中获取仅出现在特定值的条目?

时间:2015-06-23 08:37:57

标签: mysql sql

我需要在SQL表中找到始终只出现在某个值中的条目。

例如:

DeviceID    Transmission
--------    ------------
000329      Inventory
000980      Inventory
004406      Starting
000980      Stopping
000329      Inventory
004406      Inventory

现在我需要找到所有仅具有库存传输且从不启动或停止的DeviceID。在这种情况下000329。

7 个答案:

答案 0 :(得分:7)

您可以使用NOT EXISTS来排除同时具有启动或停止功能的DeviceID。

select DeviceID
from tablename t1
where not exists (select 1 from tablename t2
                  where t1.DeviceID = t2.DeviceID
                    and t2.Transmission in ('Starting','Stopping'))
  and t1.Transmission = 'Inventory'

答案 1 :(得分:3)

您可以GROUP BY使用HAVING这样的

<强>查询

SELECT DeviceID
FROM DevicesTable
GROUP BY DeviceID
HAVING SUM(CASE WHEN Transmission = 'Inventory' THEN 1 ELSE 0 END) > 1
AND SUM(CASE WHEN Transmission <> 'Inventory' THEN 1 ELSE 0 END) = 0

<强> SQL Fiddle

<强>输出

DeviceID
000329

如果您只想查看Transmission in ('Starting','Stopping'),则可以在第二个条件聚合中添加Transmission IN ('Starting','Stopping')而不是Transmission <> 'Inventory'

答案 2 :(得分:2)

您可以选择所有Transmission = 'Inventory' ID并过滤掉Transmission in('Starting', 'Stopping')中存在的ID:

select distinct(DeviceID) from YourTable
WHERE Transmission = 'Inventory'
and DeviceID not in
( select distinct(DeviceID) from YourTable
  WHERE Transmission in('Starting', 'Stopping')
);

SQL小提琴:http://sqlfiddle.com/#!9/81896/12

答案 3 :(得分:1)

假设您只有这三个具有这些名称的州('库存','开始','停止'),您可以使用:

select deviceID from table1 
group by deviceID 
having max(transmission)='Inventory'

此处使用最大是有效的,因为'开始','停止'按字母顺序排列'广告资源'

http://sqlfiddle.com/#!9/81896/8

结果是正确的 000329

答案 4 :(得分:1)

试试这个......

select *
from tablename 
where DeviceID not in 
(select DeviceID from tablename 
where Transmission in('Starting','Stopping'))
and Transmission='Inventory';

答案 5 :(得分:0)

这很简单:

-- You didn't give a name for your table
SELECT DeviceID from YourTable WHERE Transmission = 'Inventory'

答案 6 :(得分:0)

取决于您想要的内容(如果您有更多Transmission值)

SELECT DeviceID, Transmission
FROM yourtable
WHERE Transmission NOT IN ('Starting', 'Stopping')

或者

SELECT DeviceID, Transmission
FROM yourtable
WHERE Transmission = 'Inventory'