当前,我正在编写两个查询来为fieldTwo的每个可能值计算fieldOne的不同出现次数。如何在一个查询中做到这一点?谢谢
select
count(*) from(select distinct(fieldOne) from myTable where fieldTwo= 'valueOne')x
select
count(*) from(select distinct(fieldOne) from myTable where fieldTwo = 'valueTwo') y
答案 0 :(得分:1)
尝试使用CASE
语句
SELECT COUNT(DISTINCT CASE WHEN FIELDTWO= 'VALUEONE' THEN FIELDONE END) X ,
COUNT(DISTINCT CASE WHEN FIELDTWO= 'VALUETWO' THEN FIELDONE END)Y
FROM MYTABLE
答案 1 :(得分:0)
这可以通过cross apply
来完成,而无需知道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