How can I select LINK_USER_ID who has only 1 CA account and 1 SA account. There are users which have 2 CA and 1 SA or 1 CA only or 1 SA only using SQL query.
NOTE: 1 LINK_USER_ID can linked to multi LINK_CIS_NO.
Sample data
LINK_ODDS_NO | LINK_ACCT_NO | LINK_USER_ID | LINK_CIS_NO | LINK_ACCT_TYPE |
---|---|---|---|---|
124770648 | 3180879599940 | 99134982 | 3236463 | CA |
124770649 | 3180879599941 | 99134982 | 3236464 | SA |
124770650 | 3180879599942 | 99134981 | 3236465 | CA |
124770651 | 3180879599943 | 99134981 | 3236466 | SA |
124770652 | 3180879599944 | 99134984 | 3236455 | MC |
124770653 | 3180879599945 | 99134984 | 3236478 | CA |
124770654 | 3180879599946 | 99134985 | 32364688 | CA |
124770655 | 3180879599947 | 99134985 | 3236556 | SA |
124770656 | 3180879599948 | 99134986 | 3244879 | SA |
Expected result
LINK_USER_ID |
---|
99134982 |
CodePudding user response:
Aggregate by id and count conditionally:
select link_user_id
from mytable
group by link_user_id
having count(case when link_acct_type = 'CA' then 1 end) = 1
and count(case when link_acct_type = 'SA' then 1 end) = 1`.
CodePudding user response:
select LINK_USER_ID
from table
where LINK_ACCT_TYPE in ('CA', 'SA')
group by LINK_USER_ID
having count(distinct LINK_ACCT_TYPE) = 2
The query groups the data by LINK_USER_ID and then checks to see if there are two distinct values for LINK_ACCT_TYPE (CA and SA). If there are, then that LINK_USER_ID is included in the results.