Je pense que ce qui suit fait ce que vous voulez :
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
Il fait un group by
conditionnel ainsi les ID source NULL ne seront pas regroupés. Il les place ensuite en dernier en utilisant la logique dans order by
.
Je n'ai pas compris ce que vous vouliez dire par dernière occurrence. Maintenant, je pense que oui :
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
Cela rejoint les informations du dernier enregistrement (basé sur l'identifiant le plus élevé).