可是CTE不能这么做呢? ------解决方案-------------------- 你可以两次cte,比如:
;with cte as
(......),cte1 as (select * from cte where xxx)
select *
from cte1 where xxxx ------解决方案-------------------- 实践证明:可以
;WITH cte AS (SELECT 1 id UNION ALL SELECT 2),
cte2 AS
(
SELECT * FROM cte
)
SELECT a.id AS AID,B.ID AS BID FROM cte a inner join cte2 b ON a.id=b.id
;WITH cte AS (SELECT 1 id UNION ALL SELECT 2),
cte2 AS
(
SELECT * FROM cte
)
SELECT *,'FirstCTE' FROM cte2
UNION ALL
SELECT *,'SecondCTE' FROM cte
/*
id
----------- ---------
1 FirstCTE
2 FirstCTE
1 SecondCTE
2 SecondCTE
*/
------解决方案--------------------
CTE只对当前批有用
也就是说只能调用一次
;with f as
(
select * from tb
)
select * from f
--
如果再select * from f as a inner join b on ..就会报错