We have a table named device and the data looks like below.
device_id name amount status
100 abc 50 active
100 abc 100 inactive
200 xyz 150 inactive
300 pqr 100 active
400 aaa 10 active
400 bbb 20 inactive
500 hhh 30 inactive
500 qqq 40 inactive
We have to modify an existing query , a simple select query , so as to satisfy the below conditions.
- If we have duplicate device ids (ex: row 1 and row 2) , with at least one of them is active, then we have to select only active device id.
- If we have duplicate device ids which don't have any active device ids (ex: row 7 and row 8) then we can select any device id among them.
- If we don't have any duplicate device ids (ex: row 3 and row 4) then we have to select all the device ids.
So final result set should look like below,
device_id name amount status
100 abc 50 active
200 xyz 150 inactive
300 pqr 100 active
400 aaa 10 active
500 hhh 30 inactive
Existing query that we have right now is as below,
select d.DEVICE_ID, d.name, d.amount
from Device d with(nolock)