in reply to Searching (sybase) Database and SQL help (was: Neophyte needs help.)
If you just want to query the table to get each WARNING/OK NOW pair then you can do something like this:
and you could process this in perl to merge matching rows:select topic, category, date from alarms order by topic, date
Not very pretty, but it should merge the two rows. Note that this will print all the rows - not just the latest instance for each topic.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"; }
If you want the latest entry for each topic, you can do something like this:
This will give you the latest row for each topic/category pair, with NULL values for the second category/date values if the last entry in the table is a WARNING.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
There are probably other ways that this can be achieved at the SQL level...
Michael
|
|---|