使用group by计算select语句中的位列

时间:2017-11-07 08:39:34

标签: sql sql-server tsql select group-by

在这里苦苦挣扎。

我有两列(已选中和已完成),我需要分别获取计数。

Module                  Topic               Selected  Completed

Applying for finance    Application process     0   NULL
Applying for finance    Application outcome     1   NULL
Applying for finance    Registration process    1   NULL
Applying for finance    Insurance options       1   NULL
Applying for finance    Repayment options       1   NULL
Applying for finance    Application process     0   NULL
Applying for finance    Application outcome     1   1
Applying for finance    Registration process    1   1
Applying for finance    Insurance options       1   1
Applying for finance    Repayment options       1   1

如何构建select查询以返回如下

 Module                  Topic               Selected  Completed

Applying for finance    Application process     0   0
Applying for finance    Application outcome     2   1
Applying for finance    Registration process    2   1
Applying for finance    Insurance options       2   1
Applying for finance    Repayment options       2   1

我的做法是这样的,但并没有完全恢复预期的结果。

    select
m.Module,
t.Topic,
count (tu.Selected) as Selected,
count (tu.Completed) as Completed
from TopicUser tu
inner join Users u on u.Id = tu.UserId
inner join Topics t on tu.TopicId = t.TopicId
inner join Module m on m.ModuleId = t.ModuleId

group by m.Module, t.Topic, Completed 

order by Module asc

理想情况下,主题列不应重复

Selected和Completed列都是位

亲切的问候

1 个答案:

答案 0 :(得分:1)

试试这个:

 select
m.Module,
t.Topic,
count (tu.Selected) as Selected,
count (tu.Completed) as Completed
from TopicUser tu
inner join Users u on u.Id = tu.UserId
inner join Topics t on tu.TopicId = t.TopicId
inner join Module m on m.ModuleId = t.ModuleId

group by m.Module, t.Topic

order by Module asc

您有left组中的Completed列。我们不希望这样做,因为结果将按其分组,并且将返回更多行。