日付を含むテーブルT1と、日付と値を含むテーブルR2があります。R2の日付と値を取得し、これをテーブルR2から値を見つける必要があるT1の日付とグループ化するクエリを作成したいと思います。
T1
Start Date
-----------------------
2018-08-09 09:42:00.000
2018-08-09 09:46:00.000
2018-08-09 09:48:00.000
R2
Start Date | Value
-----------------------|-------
2018-08-09 09:40:00.000|1
2018-08-09 09:43:00.000|2
2018-08-09 09:44:00.000|3
そしてその結果
Start Date | Value|Original|
-----------------------|----------------
2018-08-09 09:40:00.000|1 |yes |
2018-08-09 09:43:00.000|2 |yes |
2018-08-09 09:44:00.000|3 |yes |
2018-08-09 09:42:00.000|1 |no | --> Value found in R2 table (first value before the date)
2018-08-09 09:46:00.000|3 |no | --> Value found in R2 table (first value before the date)
2018-08-09 09:48:00.000|3 |no | --> Value found in R2 table (first value before the date)
少し早いですがお礼を
1つのオプションは、おそらく最もパフォーマンスが高くありませんが、SQL Serverのどのバージョンでも機能するはずです。相関サブクエリを使用してR2
、の開始日よりも短い最新の開始日を検索しT1
ます。
WITH cte AS (
SELECT
t1.StartDate,
(SELECT TOP 1 t2.Value FROM R2 t2
WHERE t2.StartDate < t1.StartDate ORDER BY t2.StartDate DESC) Value,
'No' AS Original
FROM T1 t1
)
SELECT StartDate, Value, 'Yes' AS Original FROM R2
UNION ALL
SELECT StartDate, Value, Original FROM cte
ORDER BY Original DESC, StartDate;
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加