2010-11-04 70 views
1

我要寻找的改进,下面查询,任意输入感激地接受优化SQL,现有的使用两个全表查询扫描CTE的

with cteA as (
     select name, count(1) as "A" 
     from mytable 
     where y="A" 
     group by name 
    ), 
    cteB as (
      select name, count(1) as "B" 
      from mytable 
      where y="B" 
      group by name 

    ) 
    SELECT cteA.name as 'name', 
     cteA.A as 'count x when A', 
     isnull(cteB.B as 'count x when B',0) 
    FROM 
    cteOne 
    LEFT OUTER JOIN 
    cteTwo 
    on cteA.Name = cteB.Name 
    order by 1 

回答

3
select name, 
     sum(case when y='A' then 1 else 0 end) as [count x when A], 
     sum(case when y='B' then 1 else 0 end) as [count x when B] 
    from mytable 
    where y in ('A','B') 
    group by name 
    order by name 
+0

+1 - 很好! (15chars) – JNK 2010-11-04 14:26:20

+0

当然,如果字段Y和名称被索引,这也会很有帮助。 – HLGEM 2010-11-04 14:43:03

0

最简单的回答是:

select name, y, count(*) 
from mytable 
where y in ('A','B') 
group by name, y 

如果您需要列中的Y行值,可以使用PIVOT将Y行值移动到列中。