43

Is it possible to write a CTE within a CTE?

I want it to follow this logic, but the interpreter doesn't like this code.

with outertest as(

    with test as (
        select 
            SRnum, 
            gamenumber, 
            StartOfDistribution, 
            ApplicationNumber   
        from #main
        where startofdistribution = '2011-06-14 00:00:00.000'
        and SRnum = '313'
        --order by SRnum, gamenumber, StartOfDistribution, ApplicationNumber
    )
    select
        ApplicationNumber
        ,count(*) as RetailerAppearance
    from test
    group by ApplicationNumber
    having count(*) = 4

) select count(*) from outertest
4

1 回答 1

92

您不能像在 SQL Server 中那样嵌套 CTE,但可以通过以下方式使用多个 CTE:

;with test as 
(
    select 
        SRnum, 
        gamenumber, 
        StartOfDistribution, 
        ApplicationNumber   
    from #main
    where startofdistribution = '2011-06-14 00:00:00.000'
    and SRnum = '313'
    --order by SRnum, gamenumber, StartOfDistribution, ApplicationNumber
),
 outertest as
 (
    select
        ApplicationNumber
        ,count(*) as RetailerAppearance
    from test
    group by ApplicationNumber
    having count(*) = 4
) 
select count(*) 
from outertest
于 2013-09-10T20:50:47.470 回答