SQL Select with Distinct

时间:2017-03-25 17:11:47

标签: sql sql-server

使用此数据

Team Name Won
X    Andy  1
X    Cara  1
X    Cara  1
X    Eric  0
X    Eric  0
X    Eric  0
X    Eric  0
Y    Bill  0
Y    Dave  0
Y    Dave  1
Y    Dave  1

我希望每支球队的球员数量和获胜者数量

Team Players Winners
X       3       2
Y       2       1

是否在两个查询中:

select team, count(distinct Name) as Players from test group by team
select team, count(distinct Name) as Winners from test where Won=1 group by team

但我无法解决其中的语法问题。 TIA的帮助。约翰

3 个答案:

答案 0 :(得分:3)

您可以使用case进行条件聚合:

select team,
    count(distinct name) as Players,
    count(distinct case when won = 1 then name end) as winners
from test
group by team

答案 1 :(得分:1)

试试这个:

select team, count(distinct Name) as Players, sum(won) Winners 
from (select distinct * from test) tst 
group by team

您可以在此处进行测试:http://rextester.com/QATLK24197

答案 2 :(得分:1)

你可以按小组

来做

选择球队,计数(名称)为球员,总和(获胜)获胜者来自( 选择团队,名称,总和(明显赢得)从团队,名称的测试组中获胜 )按团队分组