COUNT(DISTINCT表达式)?

时间:2017-07-21 19:20:56

标签: sql count distinct

代码:

Select Distinct
    EE.EMPLOYEE_ID,
    EE.COLOR,
    COUNT(DISTINCT EE.COLOR) AS COLOR_COUNT
FROM #EMPLOYEEINFO EE

GROUP BY EE.EMPLOYEE_ID,
         EE.COLOR

我认为这段代码会给我每个员工ID的唯一颜色数。但是,对于所有行,COLOR_COUNT都会返回1。

任何帮助都会很棒,谢谢!

1 个答案:

答案 0 :(得分:1)

如果您想要唯一颜色的数量,请不要在color中添加group by

SELECT EE.EMPLOYEE_ID, 
       COUNT(DISTINCT EE.COLOR) AS COLOR_COUNT
FROM #EMPLOYEEINFO EE
GROUP BY EE.EMPLOYEE_ID;

此外,使用SELECT DISTINCT时几乎不需要GROUP BY