Jag tror att följande gör vad du vill:
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
Den gör en villkorlig group by
så NULL sourceids kommer inte att grupperas. Den placerar dem sedan sist med hjälp av logik i order by
.
Jag förstod inte vad du menade med den senaste händelsen. Nu tror jag att jag gör:
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
Detta ansluter till informationen från den senaste posten (baserat på högsta id).