优化sql,使用两个完整表扫描CTE';s
我正在寻找对以下查询的改进,感谢您的任何意见优化sql,使用两个完整表扫描CTE';s,sql,tsql,optimization,Sql,Tsql,Optimization,我正在寻找对以下查询的改进,感谢您的任何意见 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="
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, y, count(*)
from mytable
where y in ('A','B')
group by name, y
如果在列中需要Y行值,可以使用轴将Y行值移动到列中。当然,如果为字段Y和名称编制索引,也会很有帮助。
select name, y, count(*)
from mytable
where y in ('A','B')
group by name, y