select topic, category, date from alarms order by topic, date #### my $data = $dbh->ct_sql($query); my $previous_row; foreach (@$data) { if($previous_row && $_->[0] eq $previous_row->[0]) { print "$previous_row->[0] $previous_row->[1] $previous_row->[2] $r_->[1] $r_->[2]\n"; $previous_row = undef; } elsif($previous_row) { # There is no matching OK NOW row for this entry print "$previous_row->[0] $previous_row->[1] $previous\n"; } else { $previous_row = $_; } } # print orphan, if there is one if($previous_row) { print "$previous_row->[0] $previous_row->[1] $previous\n"; } #### select id = max(id), topic, category, date = max(date) into #tmp from alarms group by topic, category select t1.topic, t1.category, t1.date, t2.category, t2.date from #tmp t1, #tmp t2 where t1.category = "WARNING" and t2.category = "OK NOW" and t1.topic = t2.topic and t1.date < t2.date UNION select t1.topic, t1.category, t1.date, NULL, NULL from #tmp t1, #tmp t2 where t1.category = "WARNING" and t2.category = "OK NOW" and t1.topic = t2.topic and t1.date > t2.date