MySQL COUNT(CASE WHEN ... THEN DISTINCT Column)

34,988

Try this

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

  ) AS mtd
Share:
34,988

Related videos on Youtube

GGio
Author by

GGio

Updated on August 02, 2022

Comments

  • GGio
    GGio almost 2 years

    My query:

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

    I want something like:

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

    This gives an error. I can not use GROUP BY. If I add DISTINCT before CASE it does not work either it treats FieldValue column as DISTINCT but I want it to count ColumnID as distinct.

    Please help

    • Cyclonecode
      Cyclonecode
      Show the entire query. Have you tried adding the DISTINCT right before the actual case i.e: COUNT(DISTINCT CASE ...)
  • echo_Me
    echo_Me almost 10 years
    this will count unique ColumnIDs and count them yes.
  • 7H3 IN5ID3R
    7H3 IN5ID3R over 6 years
    how about multiple case statements ?
  • Crusaderpyro
    Crusaderpyro over 5 years
    anyway to have more than 1 column in the DISTINCT ? like THEN ColumnID, AnotherID. It gives a parse exception because of the comma