I want to count how many distinct ids have values of 'A' AND 'B' in column Code.
| ID | Code |
| ------------ | ------------ |
| 1 | A |
| 1 | B |
| 1 | C |
| 1 | D |
| 2 | A |
| 2 | B |
| 2 | C |
Data as fiddle
I tried using
SELECT COUNT(DISTINCT ID)
FROM tab
WHERE CODE = 'A' AND CODE = 'B';
and
SELECT COUNT(DISTINCT ID)
FROM tab AS t1
WHERE EXISTS (
SELECT 1
FROM tab
WHERE ID = t1.ID AND CODE = 'A' AND CODE = 'B'
);
Both methods count 0
Why is that?
Thank you
2条答案
按热度按时间6rvt4ljy1#
If you want count for different codes:
If you want common count of distinct ID paired with any of letters
A
orB
use this:cwtwac6a2#
I want to count how many distinct
id
s have values'A'
and'B'
in columncode
.I would recommend
group by
andhaving
; this gives you the list ofids
that have both codes (assuming no duplicate id/code).Now we can just count how many rows the above query returns to get the output you wanted:
I would expect this approachto perform better than the solution using
intersect
, because it scans the table only once.Note that it is also possible to use
exists
, as you intended in yuour second attempt (although that's one more table scan); we would just need to fix the filtering:This selects rows of code A and ensure that the given id has another row with code B.