结合多个cte

时间:2014-10-25 19:49:43

标签: sql-server-2008

是否可以将两个cte的结果与另一个cte相结合。我写了一个结合两个cte的查询。结果给出了三列数据,其中我想将第三列分组并对第二列求平均值。第二列来自案例总结陈述。

1 个答案:

答案 0 :(得分:1)

如果您询问在查询中使用CTE后是否可以重复使用它,答案是否定的。你不能这样做:

 with A
 as (
    -- query
 )
 select A.*
 from   A;

 -- this is a separate query
 select id
    ,   count(*)
 from   A
 group by 
        id

但是,只要您在一个语句中执行此操作,就可以以各种方式组合CTE。你可以这样做,它在两个CTE和最终查询中使用假设的CTE A

 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