ROW_NUMBER()SUB QUERY ISSUE

时间:2016-01-25 23:54:56

标签: sql subquery row-number

我正在尝试在特定时间段内找到活动。

可以并且将会有一个'fileno'的多条记录我想将其限制为一条记录。

SELECT   MASTER.FILENO, MASFORW.FORW_NO, MASTER.FORW_FILENO, 
         MASTER.COCO_FILENO, MASFORW.SORT_FIELD, TRACKUSR.trck_date, 
         TRACKUSR.whoami, TRACKUSR.track, TRACKUSR.rerite, 
         ROW_NUMBER() OVER (PARTITION BY  MASTER.FILENO  
                            ORDER BY TRACKUSR.TRCK_DATE DESC) AS rownum
FROM    MASFORW 
INNER JOIN  MASTER 
        ON MASFORW.FORW_NO = MASTER.FORW_NO 
FULL OUTER JOIN TRACKUSR 
        ON MASTER.FILENO = TRACKUSR.fileno
WHERE (TRACKUSR.TRCK_DATE >= DATEADD(day, 0, GETDATE())) 
  AND (TRACKUSR.TRCK_DATE < DATEADD(day, 90, GETDATE())) 
  AND (MASFORW.SORT_FIELD = N'CR' OR
                         MASFORW.SORT_FIELD = N'CJ') 
  and (rownum = 1)  

3 个答案:

答案 0 :(得分:0)

创建一个子查询,然后在外面过滤rownum。

您无法在同一查询中使用别名,因为此时您会检查别名的创建位置

SELECT *
FROM (
      SELECT ROW_NUMBER() OVER (PARTITION BY  MASTER.FILENO  
                                ORDER BY TRACKUSR.TRCK_DATE DESC) AS rownum
      FROM ...
     ) as subquery
WHERE rownum = 1

答案 1 :(得分:0)

你不能在where子句中使用别名......

有一个sql语句层次结构..

  1. from table
  2. where clause
  3. group by
  4. 选择
  5. 通过
  6. 订购

    related link

答案 2 :(得分:0)

假设查询的其余部分没问题,您可以通过替换

来清除错误
and (rownum = 1)      

having ROW_NUMBER() OVER (PARTITION BY  MASTER.FILENO  
       ORDER BY TRACKUSR.TRCK_DATE DESC) = 1