0

市内のさまざまな場所を移動する個々の車の情報 (開始時刻、終了時刻、開始場所、終了場所など) を含むトリップ テーブルがあります。また、半定期的 (15 ~ 30 分ごと) に測定された、その都市の気象条件 (気温、降水量など) の表も作成しました。

Trip Table
| TripID  |        StartTime        |       EndTime           | ....
| 1       | 2012-01-10 03:50:00.163 | 2012-01-15 04:15:40.163 |
| 2       | 2012-01-10 03:59:00.113 | 2012-01-15 04:44:25.025 |
| 3       | 2012-01-10 04:10:00.127 | 2012-01-15 04:35:36.064 |

Weather Table
| WeatherID |    ReadingTime      | .... 
| 1         | 2012-01-10 03:45:00 | 
| 2         | 2012-01-10 04:02:05 | 
| 3         | 2012-01-10 04:30:34 | 
| 4         | 2012-01-10 04:45:23 | 

これらの気象測定値は離散的であるため、(より) 連続的にするために、ID は読み取り時間を中間点とする範囲で有効であると想定しています。例えば:

  • WeatherID 1 の条件は 3:45 から 3:53:525 まで有効です
  • WeatherID 2 条件は 3:53:525 から 3:16:195 まで有効です

各旅行を天気に関連付ける旅行テーブルに外部キーを追加したいと思います。旅行の大部分に存在していたものです。たとえば、TripID 2 の完了には 42 分かかり、これは 2 つの気象測定値 (WeatherID 2 および 3) で発生します。したがって、旅行の多くは weatherID 2 ではなく weatherID 3 で発生するため、WeatherID 3 が tripID 2 レコードに割り当てられます。

これは少し複雑だと思いますが、SQL を使用して解決することは可能ですか? どんな助けでも大歓迎です。感謝。

4

1 に答える 1

0

最新バージョンの SQL Server を使用している場合、旅行の大部分をカバーする気象条件を取得するには、次のことを試してください。

with tripSegs (wxId, starttime, endTime)
As (Select w.WeatherId, 
         coalesce(n.readingTime, w.ReadingTime) startTime,
         coalesce(p.readingTime, w.ReadingTime) endTime
    From Weather w
    left Join weather p on p.ReadingTime =
        (Select Max(ReadingTime)
            From Weather
            Where ReadingTime < w.ReadingTime)
    left Join weather n on n.ReadingTime =
        (Select Min(ReadingTime)
            From Weather
            Where ReadingTime > w.ReadingTime)) 
Select t.tripId, w.wxId, 
    case when w.startTime < t.startTime then t.startTime else w.startTime end startTime,
    case when w.endTime > t.endtime then t.endtime else w.endtime end endtime,
    case when w.startTime < t.startTime then t.startTime else w.startTime end -
    case when w.endTime > t.endtime then t.endtime else w.endtime end elapsedEffectiveTime
From Trips t Join tripSegs w 
     On w.starttime < t.endtime 
 And w.endtime > t.startTime
Where case when w.startTime < t.startTime then t.startTime else w.startTime end -
      case when w.endTime > t.endtime then t.endtime else w.endtime end >  
   (Select Max(case when w.startTime < t.startTime then t.startTime else w.startTime end -
               case when w.endTime > t.endtime then t..endtime else w.endtime end) 
    from Trips t
    Join tripSegs w On w.starttime < t.endtime 
        And w.endtime > t.startTime)
于 2013-09-04T20:12:53.947 に答える