选择具有回溯和未来日期方案的正确有效日期

时间:2018-05-31 01:15:02

标签: sql sql-server date

情景1:

Table as,
IF OBJECT_ID('TEMPDB..#RUN_ID') IS NOT NULL
DROP TABLE #RUN_ID

;WITH RUN_ID as ( 

SELECT 1 AS RUN_ID,1 AS EMP_ID, '1/1/2018' STARTDT, 'A' AS VALUE
UNION
SELECT 2 AS RUN_ID,1 AS EMP_ID, '2/1/2018' STARTDT, 'A' AS VALUE
UNION
SELECT 3 AS RUN_ID,1 AS EMP_ID, '12/1/2017' STARTDT, 'A' AS VALUE
UNION
SELECT 4 AS RUN_ID,1 AS EMP_ID, '3/1/2018' STARTDT, 'A' AS VALUE
UNION
SELECT 5 AS RUN_ID,1 AS EMP_ID, '2/1/2018' STARTDT, 'A' AS VALUE
    )

SELECT * INTO #RUN_ID from RUN_ID

RUN_ID  EMP_ID  STARTDT VALUE
1   1   1/1/2018    A
2   1   2/1/2018    A
3   1   12/1/2017   A
4   1   3/1/2018    A
5   1   2/1/2018    A

RUN_ID是表中每天的增量值。 VALUE列可以相同也可以不同。 需要得出STARTDT的结果如下:

RUN_ID  EMP_ID  STARTDT VALUE
3   1   12/1/2017   A
5   1   2/1/2018    A

注意:RUN ID 5的最后记录是写入所有其他记录,其中2/1/2018的StartDt记录在目标中,RUN ID 3应该在结果中,因为它覆盖了以前的RUN ID StartDT

Scenario2:

RUN_ID  EMP_ID  STARTDT VALUE
1   1   1/1/2018    A
2   1   11/1/2017   A
3   1   12/1/2017   A
4   1   3/1/2018    A
5   1   2/1/2018    A

在这种情况下,结果应为

RUN_ID  EMP_ID  STARTDT VALUE
2   1   11/1/2017   A
3   1   12/1/2017   A
5   1   2/1/2018    A

1 个答案:

答案 0 :(得分:0)

如果OBJECT_ID('TEMPDB ..#RUN_ID')不是NULL DROP TABLE #RUN_ID

;将RUN_ID作为(

SELECT 1 AS RUN_ID,1 AS EMP_ID,CAST('1/1/2018'AS DATE)STARTDT,'A'AS VALUE 联盟 SELECT 2 AS RUN_ID,1 AS EMP_ID,CAST('11 / 1/2017'日期)STARTDT,'A'AS VALUE 联盟 SELECT 3 AS RUN_ID,1 AS EMP_ID,CAST('12 / 1 / 2017'AS DATE)STARTDT,'A'AS VALUE 联盟 SELECT 4 AS RUN_ID,1 AS EMP_ID,CAST('3/1/2018'AS DATE)STARTDT,'A'AS VALUE 联盟 SELECT 5 AS RUN_ID,1 AS EMP_ID,CAST('2/1/2018'AS DATE)STARTDT,'A'AS VALUE     )

从RUN_ID中选择* INTO #RUN_ID

SELECT * FROM( 选择 * ,LAG(STARTDT)OVER(按RUN_ID DESC的EMP_ID顺序分区)LAG_DATE ,LAG(STARTDT)结束时的情况(由RUN_ID DESC按EMP_ID顺序分区)为0然后为0 什么时候开始< LAG(STARTDT)OVER(由RUN_ID DESC按EMP_ID顺序分区)然后0结束1结束SCD_IND  FROM( 选择 * ,RANK()超过(按EMP_ID划分,按RUN_ID DESC开始订购)RN  来自#RUN_ID  ) 一个 A.RN = 1 )A SERE_IND = 0

RUN_ID EMP_ID STARTDT VALUE RN LAG_DATE SCD_IND 5 1 2018-02-01 A 1 NULL 0 3 1 2017-12-01 A 1 2018-03-01 0 2 1 2017-11-01 A 1 2017-12-01 0