MySQL – Conditional COUNT with GROUP BY

If droid_v can only be 0, 1, 2, 3, or 4, then COUNT(DISTINCT) will never return more than 5, since there are only five possible values. Is that what you want? If so, then try this:

SELECT puid, COUNT(DISTINCT CASE WHEN droid_v > 0 THEN droid_v ELSE 0 END) - 1 AS droid /* -1 for the case where droid_v is 0 */
     , COUNT(DISTINCT sig_v) AS sig
     , SUM(NoExt)  AS hits

Update: Oops, sorry, the above is not quite right as there might not be a zero.
It should be:

SELECT puid, COUNT(DISTINCT CASE WHEN droid_v > 0 THEN droid_v END) AS droid

If, on the other hand, you want a count of all the rows where droid_v > 0, then I think you want this:

SELECT puid, SUM(CASE WHEN droid_v > 0 THEN 1 ELSE 0 END) AS droid
     , COUNT(DISTINCT sig_v) AS sig
     , SUM(NoExt)  AS hits

Hope this helps.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)