如何选择日期和上一个日期

时间:2019-05-30 10:44:20

标签: sql-server sql-server-2016

我有一个推荐记录表,其中包含开始日期和结束日期。如果此人以前曾进行过转诊,则需要检索当前转诊之前的转诊开始和结束日期。

任何想法将不胜感激!

我希望实现的示例

Per ID    Ref ID    Refrl_Start_D    Refrl_End_D    Prev_Refrl_S    Prev_Refrl_S
1         5         10/10/2018       Null           01/02/2018      03/03/2018
2         4         05/04/2018       Null           01/01/2017      01/03/2017
1         3         01/02/2018       03/03/2018     02/01/2017      20/01/2017
1         2         02/01/2018       20/01/2018     Null            Null
2         1         01/01/2018       01/03/2018     Null            Null

已尝试添加按人员分组的排名计算。我的计划是创建另一个偏移量为1的表并将其联接(即,将引用5与4联接在一起)。但是我不知道如何正确地加入。

SELECT DIM_PERSON_ID,
       FACT_REFERRAL_ID,
       REFRL_START_DTTM,
       REFRL_END_DTTM
FROM FACT_REFERRALS;

2 个答案:

答案 0 :(得分:2)

您可以在此处使用LAG

SELECT DIM_PERSON_ID,
       FACT_REFERRAL_ID,
       REFRL_START_DTTM,
       REFRL_END_DTTM
       PrevStart = LAG(REFRL_START_DTTM)
                       OVER(PARTITION BY DIM_PERSON_ID 
                           ORDER BY REFRL_START_DTTM DESC),
       PrevEnd = LAG(REFRL_END_DTTM)
                     OVER(PARTITION BY DIM_PERSON_ID 
                         ORDER BY REFRL_END_DTTMDESC)
FROM FACT_REFERRALS R;

答案 1 :(得分:0)

您应该能够使用CTE构造它,以便根据引荐日期为每条记录计算排名/行数,然后将CTE加入自身以获取先前的引荐。例如:

WITH RANKED_REFERRALS AS (
  SELECT DIM_PERSON_ID,
         FACT_REFERRAL_ID,
         REFRL_START_DTTM,
         REFRL_END_DTTM,
         ROW_NUMBER() OVER(PARTITION BY DIM_PERSON_ID ORDER BY REFRL_START_DATE) AS ROWNUM
  FROM FACT_REFERRALS
)
SELECT A.DIM_PERSON_ID,
       A.ACT_REFERRAL_ID,
       A.REFRL_START_DTTM,
       A.REFRL_END_DTTM,
       B.REFRL_START_DTTM,
       B.REFRL_END_DTTM
FROM RANKED_REFERRALS A
LEFT JOIN RANKED_REFERRALS B ON B.DIM_PERSON_ID = A.DIM_PERSON_ID AND B.ROWNUM = A.ROWNUM - 1