Wednesday, 18 September 2013

SQL - Using sum but optionally using default value for row

SQL - Using sum but optionally using default value for row

Given tables
asset
col - id
date_sequence
col - date
daily_history
col - date
col - num_error_seconds
col - asset_id
historical_event
col - end_date
col - asset_id
I'm trying to count up all the daily num_error_seconds for all assets in a
given time range in order to display "Percentage NOT in error" by day. The
catch is if there is a historical_event involving an asset that has an
end_date beyond the sql query range, then daily_history should be ignored
and a default value of 86400 seconds (one day of error_seconds) should be
used for that asset
The query I have that does not use the historical_event is:
select ds.date,
IF(count(dh.time) = 0,
100,
100 - (100*sum(dh.num_error_seconds) / (86400 * count(*)))
) percent
from date_sequence ds
join asset a
left join daily_history dh on dh.date = ds.date and dh.asset_id=a.asset_id
where ds.date >= in_start_time and ds.date <= in_end_time
group by ds.thedate;
To build on this is beyond my SQL knowledge. Because of the aggregate
function, I cannot simply inject 86400 seconds for each asset that is
associated with an event that has an end_date beyond the in_end_time.
Can this be accomplished in one query? Or do I need to stage data with an
initial query?

No comments:

Post a Comment