简体   繁体   English

使用两个全表扫描CTE优化现有查询

[英]Optimizing sql, existing query using two full table scans CTE's

I am looking for an improvement to the below query, any input gratefully received 我正在寻找以下查询的改进,感谢收到的所有输入

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 
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

The simplest answer is: 最简单的答案是:

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

You can use a PIVOT to move Y row values into columns, if you need them in columns. 如果需要在列中使用Y值,则可以使用PIVOT将Y行值移动到列中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM