Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CTE within a CTE

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 
like image 267
sion_corn Avatar asked Sep 10 '13 20:09

sion_corn


People also ask

Can you put a CTE inside a CTE?

Not only can you define multiple CTEs and reference them in a single SELECT statement, but you can also have a CTE that references another CTE. In order to do this all you need to do is define the referenced CTE prior to using it. Here is an example where my first CTE is referenced inside the second CTE definition.

Can we join two CTE?

A straightforward question deserves a straightforward answer: yes, you can. Now that you know how to use multiple CTEs, writing a CTE that references another CTE is just a variation of what you've learned. Since it's a variation, I think it's best to show you how to do it using an example you're already familiar with.

Can CTE be nested?

Nested CTEsCommon Table Expressions can be also nested. This means having multiple CTEs in the same query where at least one CTE refers to another CTE.


1 Answers

You can't nest CTEs like that in SQL Server but you can use multiple CTEs the following way:

;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 
like image 77
Taryn Avatar answered Sep 27 '22 16:09

Taryn