I need to find entries in my SQL table that always and only appear in a certain value.
For example:
DeviceID Transmission
-------- ------------
000329 Inventory
000980 Inventory
004406 Starting
000980 Stopping
000329 Inventory
004406 Inventory
Now I need to find all DeviceIDs that only have Inventory Transmissions and never Starting or Stopping. In this case 000329.
To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.
The SQL EXCEPT operator is used to exclude like rows that are found in one query but not another. It returns rows that are unique to one result. To use the EXCEPT operator, both queries must return the same number of columns and those columns must be of compatible data types.
You can use NOT EXISTS
to exclude DeviceID's that also have Starting or Stopping.
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'
You can use GROUP BY
with HAVING
like this
Query
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
OUTPUT
DeviceID
000329
If you only want to check against Transmission in ('Starting','Stopping')
, you can add Transmission IN ('Starting','Stopping')
instead of Transmission <> 'Inventory'
in the second conditional aggregation.
You can select all Transmission = 'Inventory'
ids and filter out those exist in Transmission in('Starting', 'Stopping')
:
select distinct(DeviceID) from YourTable
WHERE Transmission = 'Inventory'
and DeviceID not in
( select distinct(DeviceID) from YourTable
WHERE Transmission in('Starting', 'Stopping')
);
SQL Fiddle: http://sqlfiddle.com/#!9/81896/12
Try this...
select *
from tablename
where DeviceID not in
(select DeviceID from tablename
where Transmission in('Starting','Stopping'))
and Transmission='Inventory';
Asuming you have only these three states with these names ('Inventory', 'Starting', 'Stopping') you could use:
select deviceID from table1
group by deviceID
having max(transmission)='Inventory'
Using max here is valid because 'Starting', 'Stopping' are alphabetically orderd after 'Inventory'.
http://sqlfiddle.com/#!9/81896/8
The result is the correct 000329.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With