公用表表达式和透视表

时间:2011-03-23 18:00:05

标签: sql sql-server tsql sql-server-2008

Iam尝试sql查询,但我无法做某事。我想在此查询中使用row_number进行分页,但我无法弄清楚我需要在“row_number之间”声明。感谢任何帮助。

  WITH cte_ana
     AS (SELECT movie_id,
                id,
                tag_id
         FROM   dt_movieTag)
SELECT Kayit.*,
       ROW_NUMBER() OVER (ORDER BY movie_id) as RowNum
FROM   cte_ana PIVOT(MAX(id) FOR tag_id IN ([3], [5], [9]))AS Kayit
where  Kayit.[3] is not null
       and kayit.[5] is not null
       and kayit.[9] is not null
order  by movie_id  

例如,我想通过此选择此查询中的少数数据(其中RowNum介于0和25之间)

1 个答案:

答案 0 :(得分:3)

您不能在row_number子句中使用where,因此需要嵌套CTE。 (显然,如果你想要第一个 25行,你可以使用TOP (25)

WITH cte_ana
     AS (SELECT movie_id,
                id,
                tag_id
         FROM   dt_movieTag),
cte2 AS
(         
SELECT Kayit.*,
       ROW_NUMBER() OVER (ORDER BY movie_id) as RowNum
FROM   cte_ana PIVOT(MAX(id) FOR tag_id IN ([3], [5], [9]))AS Kayit
where  Kayit.[3] is not null
       and kayit.[5] is not null
       and kayit.[9] is not null
)
SELECT *
FROM   cte2
WHERE RowNum <= 25      
order  by movie_id