Mysql
 sql >> Database >  >> RDS >> Mysql

raggruppare per valori non nulli

Penso che quanto segue faccia quello che vuoi:

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

Fa un group by condizionale quindi i sorgenti NULL non verranno raggruppati. Quindi li mette per ultimi usando la logica in order by .

Non ho capito cosa intendevi per ultima occorrenza. Ora penso di 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

Questo si unisce alle informazioni dell'ultimo record (basato sull'ID più alto).