MySQL COUNT(CASE WHEN ...那么DISTINCT列)

时间:2014-05-20 18:05:08

标签: mysql sql count case distinct

我的查询:

COUNT(
    CASE WHEN YEAR(FieldValue) = YEAR(CURDATE()) 
    AND MONTH(FieldValue) = MONTH(CURDATE())
    THEN 1
    END
) AS mtd

我想要类似的东西:

COUNT(
    CASE WHEN YEAR(FieldValue) = YEAR(CURDATE()) 
    AND MONTH(FieldValue) = MONTH(CURDATE())
    THEN DISTINCT ColumnID
    END
) AS mtd

这会出错。我不能使用 GROUP BY 。如果我在CASE之前添加DISTINCT它不起作用,它将FieldValue列视为DISTINCT,但我希望它将ColumnID计为不同。

请帮忙

1 个答案:

答案 0 :(得分:19)

试试这个

  COUNT(DISTINCT(
    CASE WHEN YEAR(FieldValue) = YEAR(CURDATE()) 
    AND MONTH(FieldValue) = MONTH(CURDATE())
    THEN ColumnID 
    END )

  ) AS mtd