Reputation: 1045
Currently I'm writing two queries to count distinct occurrences of fieldOne for each possible value of fieldTwo. How can I do this in one query? Thanks
select
count(*) from(select distinct(fieldOne) from myTable where fieldTwo= 'valueOne')x
select
count(*) from(select distinct(fieldOne) from myTable where fieldTwo = 'valueTwo') y
Upvotes: 0
Views: 37
Reputation: 108995
This can be done with cross apply
to remove the need to know the possible values in fieldTwo
:
select twos.FieldTwo, count(1)
from (select distinct fieldTwo from MyTable) twos
cross apply (select distinct t.fieldOne
from MyTable t
where t.fieldTwo = twos.FieldTwo) ones
group by twos.FieldTwo
Upvotes: 0
Reputation: 5893
Try using CASE
statement
SELECT COUNT(DISTINCT CASE WHEN FIELDTWO= 'VALUEONE' THEN FIELDONE END) X ,
COUNT(DISTINCT CASE WHEN FIELDTWO= 'VALUETWO' THEN FIELDONE END)Y
FROM MYTABLE
Upvotes: 1