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
Related videos on Youtube
Author by
GGio
Updated on August 02, 2022Comments
-
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
-
CyclonecodeShow the entire query. Have you tried adding the
DISTINCT
right before the actual case i.e:COUNT(DISTINCT CASE ...)
-
-
echo_Me almost 10 yearsthis will count unique ColumnIDs and count them yes.
-
7H3 IN5ID3R over 6 yearshow about multiple case statements ?
-
Crusaderpyro over 5 yearsanyway to have more than 1 column in the DISTINCT ? like THEN ColumnID, AnotherID. It gives a parse exception because of the comma