我正在寻找对以下查询的改进,感激收到任何输入
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
答案 0 :(得分: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
答案 1 :(得分:0)
最简单的答案是:
select name, y, count(*)
from mytable
where y in ('A','B')
group by name, y
如果在列中需要,可以使用PIVOT将Y行值移动到列中。