在SQL Server中使用Case When语句时的唯一计数

时间:2019-02-08 19:26:13

标签: sql-server distinct case-when

在使用case when和SQL Server中的case时,我很难获得正确的distance计数。

我有一个用于计数(区别TA_STUDENT_ID)的列,用于计算正确的计数。然后,我有2个其他列,其中我按TA_LOCATION进行计数,并且TA_LOCATION下每行的总数必须加到DISTINCT TA_STUDENT_ID的COUNT上。我需要帮助才能做到这一点。这是我的查询:

SELECT 
count  (distinct TA_STUDENT_ID) as 'count',
COUNT (CASE WHEN (TA_LOCATION = 'CCC') THEN 'CCC'  END) AS 'CCC',
COUNT(CASE WHEN (TA_LOCATION = 'SCCDC') THEN 'SCCDC'  END) AS 'SCCDC',      
[TA_AW_ID]
FROM  [S85_TA_ACYR]
group by   [TA_AW_ID]
order by  [TA_AW_ID]

我想要的结果是TA_LOCATION列中每一行的总数应总计并与我的COUNT DISTINCT TA_STUDENT_ID列中的行数相匹配。

2 个答案:

答案 0 :(得分:1)

DISTINCT内的COUNT()中使用CASE表达式:

SELECT COUNT(DISTINCT TA_STUDENT_ID) as 'count',
       COUNT(DISTINCT CASE WHEN (TA_LOCATION = 'CCC') THEN TA_STUDENT_ID  END) AS 'CCC',
       COUNT(DISTINCT CASE WHEN (TA_LOCATION = 'SCCDC') THEN TA_STUDENT_ID  END) AS 'SCCDC',      
       [TA_AW_ID]
FROM  [S85_TA_ACYR]
GROUP BY [TA_AW_ID]
ORDER BY [TA_AW_ID];

答案 1 :(得分:1)

您还可以对后两个字段使用SUM(),如下所示:

SELECT
    Count = COUNT(DISTINCT TA_STUDENT_ID)
    ,CCC = SUM(CASE WHEN ( TA_LOCATION = 'CCC' ) THEN 1 ELSE 0 END)
    ,SCCDC = SUM(CASE WHEN ( TA_LOCATION = 'SCCDC' ) THEN 1 ELSE 0 END)
    ,TA_AW_ID
FROM S85_TA_ACYR
GROUP BY TA_AW_ID
ORDER BY TA_AW_ID