0

与えられたテーブル

asset
  col - id
date_sequence
  col - date
daily_history
  col - date
  col - num_error_seconds
  col - asset_id
historical_event
  col - start_date
  col - end_date
  col - asset_id

日ごとに「エラーでない割合」を表示するために、特定の時間範囲内のすべてのアセットの毎日の num_error_seconds をすべて数えようとしています。問題は、end_date が SQL クエリの範囲を超える資産に関連する history_event がある場合、daily_history を無視し、その資産に対してデフォルト値の 86400 秒 (error_seconds の 1 日) を使用する必要があることです。

history_event を使用しないクエリは次のとおりです。

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;

これに基づいて構築することは、私の SQL の知識を超えています。集計関数のため、in_end_time を超える end_date を持つイベントに関連付けられている各アセットに単純に 86400 秒を挿入することはできません。

Sample Data
Asset
1
2

Date Sequence
2013-09-01
2013-09-02
2013-09-03
2013-09-04

Daily History
2013-09-01, 1400, 1
2013-09-02, 1501, 1
2013-09-03, 1420, 1
2013-09-04, 0, 1
2013-09-01, 10000, 2
2013-09-02, 20000, 2
2013-09-03, 30000, 2
2013-09-04, 40000, 2

Historical Event
start_date, end_date, asset_id
2013-09-03 12:01:03, 2014-01-01 00:00:00, 1

このサンプル データで期待できることは、これらの資産がエラーになっている割合です。

2013-09-01 => 100 - (100*(1400 + 10000))/(86400*2)
2013-09-02 => 100 - (100*(1501 + 20000))/(86400*2)
2013-09-03 => 100 - (100*(1420 + 30000))/(86400*2)
2013-09-04 => 100 - (100*(0 + 40000))/(86400*2)

例外: 優先すべき歴史的出来事がありました。それは 9 月 3 日に発生し、無制限です (終了日が将来であるため、計算は次のように変更されます。

2013-09-01 => 100 - (100*(1400 + 10000))/(86400*2)
2013-09-02 => 100 - (100*(1501 + 20000))/(86400*2)
2013-09-03 => 100 - (100*(86400 + 30000))/(86400*2)
2013-09-04 => 100 - (100*(86400 + 40000))/(86400*2)

start_date が「in_end_time」より前で end_time が in_end_time より後の履歴イベントがある場合、アセット 1 の num_error_seconds は 1 日分のエラー秒数で上書きされます

これは 1 つのクエリで実行できますか? または、最初のクエリでデータをステージングする必要がありますか?

4

1 に答える 1

1

私はあなたがこのようなものを求めていると思います:

Select
    ds.date,
    100 - 100 * Sum(
        case
            when he.asset_id is not null then 86400 -- have a historical_event
            when dh.num_error_seconds is null then 0 -- no daily_history record
            else dh.num_error_seconds
        end
    ) / 86400 / count(a.id) as percent -- need to divide by number of assets
From
    date_sequence ds
        cross join
    asset a
        left outer join
    daily_history dh 
        on a.id = dh.asset_id and
           ds.date = dh.date
        left outer join (
            select distinct -- avoid counting multiple he records
                asset_id
            from
                historical_event he
            Where
                he.end_date > in_end_time
        ) he
        on a.id = he.asset_id    
Where
    ds.date >= in_start_time and
    ds.date <= in_end_time -- I'd prefer < here
Group By
    ds.date

フィドルの例

于 2013-09-18T23:20:07.830 に答える