14

我必须对 WITH 查询进行查询,例如

; WITH #table1  
(  
SELECT id, x from ... WHERE....  
UNION ALL  
 SELECT id, x from ... WHERE...  
)  

WITH #table2  
(  
 SELECT DISTINCT tbl_x.*,ROW_NUMBER() OVER (order by id) as RowNumber  
WHERE id in ( SELECT id from #table1)  
)  

SELECT * FROM #table2 WHERE RowNumber > ... and ...

所以我必须在 WITH 上使用 WITH,然后在第二个 WITH 上使用 SELECT,我该怎么做?

4

1 回答 1

29

您可以在关键字之后定义多个 CTE,方法是WITH用逗号分隔每个 CTE。

WITH T1 AS
(
    SELECT id, x from ... WHERE....
    UNION ALL
    SELECT id, x from ... WHERE...
)
, T2 AS
(
    SELECT DISTINCT tbl_x.*, ROW_NUMBER() OVER (order by id) as RowNumber
    WHERE id in ( SELECT id from T1 )
)
SELECT * FROM T2 WHERE RowNumber > ... and ...

http://www.4guysfromrolla.com/webtech/071906-1.shtml

于 2012-10-30T15:24:41.677 回答