SQL Server:通过一个字段中的另一个字段中的值来统计不同的出现次数

时间:2019-03-05 07:21:20

标签: sql-server

当前,我正在编写两个查询来为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

2 个答案:

答案 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