简体   繁体   中英

SQL: find one to many in one table

there is a table: t1

Id | Acc Status| Acc Type| 
-----------------------------------------
1  |Online     | home
2  |Offine     | work
3  |Declined   | work
1  |Activated  | home

.

Question is: need to find all Id which has 'Acc Status' = Online AND 'Acc Status' = Activated

You can try below query -

SELECT id
FROM T1
WHERE AccStatus IN ('Online', 'Activated')
GROUP BY id
HAVING COUNT(DISTINCT AccStatus) = 2;

You must group by id and count the distinct values of accstatus :

select id 
from t1
where accstatus in ('Online', 'Activated')
group by id
having count(distinct accstatus) = 2

If you need the ids that have only these accstatus values:

select id 
from t1
group by id
having
  count(distinct accstatus) = 2
  and 
  sum(case when accstatus not in ('Online', 'Activated') then 1 else 0 end) = 0

Try this below query

SELECT id
FROM Table_name
WHERE AccStatus = 'Online' 
and id IN (SELECT id FROM Table_name wHERE AccStatus = 'Activated')
select DiSTINCT Id
from t1
where [Acc Status] in ("Online", "Activated")

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM