sql >> Base de Datos >  >> RDS >> Mysql

agrupar por valores no nulos

Creo que lo siguiente hace lo que quieres:

SELECT *, (To_days(date_expires)-TO_DAYS(NOW())) as dayDiff, COUNT(id) AS change_count
FROM mytable
GROUP BY (case when source_id is null then id else source_id end)
HAVING dayDiff < 4 
ORDER BY (case when source_id is null then 1 else 0 end), date_created DESC

Hace un group by por lo que los sourceid NULL no se agruparán. Luego los coloca en último lugar usando la lógica en order by .

No entendí a qué te referías con última ocurrencia. Ahora creo que sí:

SELECT coalesce(s.id, mytable.id) as id,
       max(case when s.maxid is not null and s.maxid = myable.id then mytable.name
                when s.maxid is null then NULL
                else mytable.name
           end) as name,
       (To_days(date_expires)-TO_DAYS(NOW())) as dayDiff, COUNT(id) AS change_count
FROM mytable left outer join
     (select source_id, MAX(id) as maxid
      from mytable
      where source_id is not null
      group by source_id
     ) s
     on mytable.id = s.maxid
GROUP BY (case when source_id is null then id else source_id end)
HAVING dayDiff < 4 
ORDER BY (case when source_id is null then 1 else 0 end), date_created DESC

Esto une la información del último registro (basado en la identificación más alta).