我有一张包含历史信息的表格,如下所示。
表A
switchMap
表B
ID Set_Date Reason pk
1 1/1/17 denied 1
1 1/2/17 approved 2
当set_date介于startDate和EndDate
之间时,我需要最新的值示例:
StartDate EndDate ID
1/1/17 1/2/17 1
有没有更简单的方法来提取我所要求的内容?
最终结果应为:
SELECT *
FROM(
SELECT *, DENSE_RANK() OVER (PARTITION BY ID ORDER BY SET_DATE DESC) AS RNK
FROM TableB B
INNER JOIN TABLEA ON B.ID = A.ID
AND A.SET_DATE BETWEEN B.STARTDATE AND B.ENDDATE
--BUT TWO VALUES APPLY HERE AND I ONLY WANT ONE VALUE, THE LATEST ENTRY OF THE SET OF DATA THAT FALLS BETWEEN THE TWO DATES. SO IS THE BEST APPROACH TO ADD A RNK AND SUBQUERY?
)
WHERE 1=1
AND RNK = 1
答案 0 :(得分:3)
一种方法是使用FIRST_VALUE
窗口函数。
SELECT DISTINCT A.ID, FIRST_VALUE(A.REASON) OVER (PARTITION BY A.ID ORDER BY A.SET_DATE DESC) AS Reason
FROM TableB B
INNER JOIN TABLEA A ON B.ID = A.ID
AND A.SET_DATE BETWEEN B.STARTDATE AND B.ENDDATE