简体   繁体   English

SQL 服务器 - CTE 内的 CTE

[英]SQL Server - CTE inside a CTE

I have this query:我有这个查询:

WITH months(dt) AS 
   (SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS dt 
    UNION ALL
    SELECT dateadd(month, -1, dt)
    FROM months)
SELECT 
top (datediff(month, '2020-01-01', DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1)) + 1) 
YEAR(months.dt) yr, MONTH(months.dt) mnth
FROM months
OPTION (maxrecursion 0);

What I need is that the last Select result is a CTE expression so I can use it on other select.我需要的是最后一个 Select 结果是一个 CTE 表达式,所以我可以在其他 select 上使用它。

I have tried this:我试过这个:

WITH months(dt) AS 
   (SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS dt 
    UNION ALL
    SELECT dateadd(month, -1, dt)
    FROM months),
    cte2 as (
SELECT 
top (datediff(month, '2020-01-01', DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1)) + 1) 
YEAR(months.dt) yr, MONTH(months.dt) mnth
FROM months
OPTION (maxrecursion 0)
)

But I get an error, Im doing something wrong for sure.但我得到一个错误,我肯定做错了什么。

Any advice?有什么建议吗?

You're almost there.您快到了。 You need to add the final SELECT over cte2 .您需要在cte2 SELECT For example:例如:

WITH 
months (dt) AS 
   (SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS dt 
    UNION ALL
    SELECT dateadd(month, -1, dt)
    FROM months),
cte2 as (
    SELECT 
    top (datediff(month, '2020-01-01', 
           DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1)) + 1) 
    YEAR(months.dt) yr, MONTH(months.dt) mnth
    FROM months
)
SELECT * from cte2
OPTION (maxrecursion 0)

This way you can chain two, three, four, etc CTEs one after the other.这样,您可以一个接一个地链接两个、三个、四个等 CTE。 Any CTE can JOIN, use, or combine any of the CTEs defined previously.任何 CTE 都可以加入、使用或组合之前定义的任何 CTE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM