如何加入2 row_numbers

时间:2014-05-09 21:49:47

标签: java

Im trying to do a query where I want to join the row_numbers RN and RN1 so as to remove the     duplicate rows as shown BOLD in the result set. 
   

    WITH CTE AS (
    SELECT
    PrevEndDate = LAG(edate,1) OVER (PARTITION BY id ORDER BY id)
    , PrevStartDate = LAG(sdate,1) OVER (PARTITION BY id ORDER BY id)
    , p.id, p.edate
    , ROW_NUMBER() OVER (PARTITION BY p.id ORDER BY p.id) as RN1
    FROM table p
    )
    SELECT 
    t.id, t.sdate, t.edate
    , (ROW_NUMBER() OVER (PARTITION BY t.id ORDER BY t.id)) AS RN
    , CTE.RN1
    , CASE 
       WHEN  CTE.PrevEndDate > t.sdate
       THEN DATEDIFF(day,CTE.PrevStartDate,t.sdate) 
      ELSE
        DATEDIFF(day,t.sdate,t.edate)
      END 
    FROM table t 
    INNER JOIN CTE ON CTE.id= t.id AND CTE.edate= t.edate
    --AND RN1 = RN

提前致谢!

1 个答案:

答案 0 :(得分:0)

您无法在select中定义别名,然后在from(或where)中使用该别名。您可以将其移动到子查询中。类似的东西:

with cte as (. . .)
SELECT . . .
FROM (SELECT t.*, ROW_NUMBER() OVER (PARTITION BY t.PRTCPNT_DCN ORDER BY t.PRTCPNT_DCN) as RN
      FROM PRTCPNT_ELIG_SPAN_T t 
     ) t INNER JOIN
     CTE
     ON CTE.PRTCPNT_DCN = t.PRTCPNT_DCN AND
        CTE.PRTCPNT_ELIG_END_DATE = t.PRTCPNT_ELIG_END_DATE AND
        CTE.RN1 = t.RN;