I have a table that has columns Name, Series and Season.
Name | series | season |
---|---|---|
abc | alpha | s1 |
abc | alpha | s2 |
pqr | alpha | s1 |
xyz | beta | s2 |
xyz | gamma | s3 |
abc | theta | s1 |
I am trying to extract the number of people who have watched only the series ‘alpha’, and not any other series.
How to get this count?
On giving the "where series=’alpha’ " condition, I get the counts of people who watched alpha, but not the counts of those who watched only alpha eg: abc has watched alpha as well as theta, but pqr has watched only alpha.
5
Answers
If you really want to get the number of such people only, without their name or any further information, you can use a
NOT EXISTS
clause like this:Thus, you can set your condition the person must not appear in any other series but the ‘alpha’ one.
If the same name can occur in different seasons, you can add a
DISTINCT
to count them only once. This should only be done if really required because it can slow down the query:If your description is incorrect and you need also other information, you might do better with a
GROUP BY
clause etc.Try out here: db<>fiddle
You can use subquery, like this:
You could use a subquery to get only the names which have watched only distinct series and then filter in the where condition your specific serie
https://dbfiddle.uk/n0PavP4H
You can use like below
select sum(Record) as Count from (select count() as Record from yourtable where series=’alpha’
group by series,name having count()=1) as data
Check below link
https://dbfiddle.uk/1Y3WZT23
I added some new cases to your table to see other anomalies that can happen. This is how it looks like now:
I maybe overcomplicated, but it can provide the correct result for your problem; you just need to
COUNT()
it. I tested other SQL queries under your question on my this table, but not all of them showed the correct figure. I doesn’t recommend to useNOT IN ( sub query )
for the following reasons:Please find my code here:
Hope it helps!