Is it possible to combine a result of two cte to another cte. I wrote a query combining two cte. The result gave a three column data in which I want to group the third column and averaging the second column. The second column resulted from a case sum statement.
Asked
Active
Viewed 3,814 times
-1
-
Post the query you tried already. – Rahul Oct 25 '14 at 19:59
-
http://stackoverflow.com/questions/18941275/joining-multiple-common-table-expressions I hope that helps. Is that what you are looking to do – Quizzys Oct 25 '14 at 20:00
1 Answers
1
If you are asking whether you can re-use CTEs after they have been used in a query, the answer is no. You can't do this:
with A
as (
-- query
)
select A.*
from A;
-- this is a separate query
select id
, count(*)
from A
group by
id
You can, however, combine CTEs in all kinds of ways, as long as you do it in a single statement. You can do this, which uses the hypothetical CTE A
in two CTEs and the final query:
with A
as (
-- some query
)
, ACustomers
as (
select *
from Customers
join A
on ....
)
, AVendors
as (
select *
from Vendors
join A
on ....
)
select A.StateId
, ACount = COUNT(*)
, CustomerCount = (select count(*) from ACustomers ac where ac.StateId = A.StateId )
, VendorCount = (select count(*) from AVendors av where av.StateId = A.StateId )
from A
group by
A.StateId

Ann L.
- 13,760
- 5
- 35
- 66
-
@Arvin I don't know, but I've done at least 8 on occasion. I looked and couldn't find a limit stated anywhere. – Ann L. Oct 27 '14 at 13:13