类别明智的COUNT DISTINCT查询

时间:2014-08-05 08:44:47

标签: mysql

SELECT col1, col2, 
SUM(CASE WHEN category='CAT1' THEN val END) as SUMvalCAT1, 
SUM(CASE WHEN category='CAT2' THEN val END) as SUMvalCAT2 
from TABLENAME 
GROUP BY col1, col2;

这是一个有效的查询,我在val组中为两个不同的categorycol1,col2

现在同样我希望另一列的不同值的Count表示XYZ。 所以,如果我尝试:

SELECT col1, col2, 
SUM(CASE WHEN category='CAT1' THEN val END) as SUMvalCAT1, 
SUM(CASE WHEN category='CAT2' THEN val END) as SUMvalCAT2,
COUNT(CASE WHEN category='CAT1' THEN DISTINCT XYZ END) as CAT1dist,
COUNT(CASE WHEN category='CAT2' THEN DISTINCT XYZ END) as CAT2dist
from TABLENAME 
GROUP BY col1, col2;

但这会引发错误。

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DISTINCT XYZ END) as CAT1dist,
COUNT(CASE WHEN category='CAT2' THEN DISTI' at line 4

可能出现什么问题?

2 个答案:

答案 0 :(得分:2)

DISTINCT必须在COUNT参数的开头出现:

COUNT(DISTINCT CASE ... END)

它是COUNT函数的特殊修饰符,而不是可以任意应用于值的东西。

答案 1 :(得分:1)

您需要将DISTINCT关键字放在CASE之前,如下所示:

SELECT col1, col2, 
SUM(CASE WHEN category='CAT1' THEN val END) as SUMvalCAT1, 
SUM(CASE WHEN category='CAT2' THEN val END) as SUMvalCAT2,
COUNT(DISTINCT CASE WHEN category='CAT1' THEN XYZ END) as CAT1dist,
COUNT(DISTINCT CASE WHEN category='CAT2' THEN XYZ END) as CAT2dist
from TABLENAME 
GROUP BY col1, col2;

SQLFiddle