我的查询:

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视为不重复的。

请帮忙

最佳答案

试试这个

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

  ) AS mtd

关于MySQL COUNT(当...然后是DISTINCT列时的情况),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23766902/

10-08 22:35