Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

t-sql WITH on WITH

I have to make query on WITH query, something like

; 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 ...

So I have to use WITH on WITH and then SELECT on second WITH, How I can do that?

like image 308
Mertez Avatar asked Oct 30 '12 15:10

Mertez


1 Answers

You can define multiple CTEs after the WITH keyword by separating each CTE with a comma.

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

like image 149
Tim Schmelter Avatar answered Nov 26 '22 07:11

Tim Schmelter