I have the following table. What I need is an sql query that will analyze two/more rows with the same id and: (1) CASE 'Result' is the same for both rows, print 'Passed'; (2) CASE 'Result' is not the same for both rows, print 'Failed'.
ID Result
73 2000 Passed
73 2000
43 2000 Failed
43 1003
Is it all possible??
One option uses EXISTS
:
SELECT DISTINCT ID
FROM yourTable t1
WHERE NOT EXISTS (SELECT 1 FROM yourTable t2 WHERE t1.ID = t2.ID AND t2.Result <> t1.Result);
Another option uses aggregation:
SELECT ID
FROM yourTable
GROUP BY ID
HAVING COUNT(DISTINCT Result) = 1;
If you want one row per id, then use group by
:
select id,
(case when min(result) = max(result) then 'Passed'
else 'Failed'
end) as flag
from t
group by id;
If you want the value on all rows of your original table, then it is simple:
select id,
(case when not exists (select 1
from t t2
where t2.result) = t.result
)
then 'Passed' else 'Failed'
end) as flag
from t
group by id;
However, putting the result on one row is problematic. There is no way to distinguish the rows, so it is more challenging (not impossible, but I suspect one of the above solves your real problem).
Try below:
select id, case when count (distinct result)=1 then 'Passed' else 'Failed' end
group by id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.