我得到了这样的表,我想在其中计算"WeekCount";因此;完成";已计数,但按周期和一周分组。|
ID | 天 | 周期 | 周完成|||
---|---|---|---|---|---|
1 | 1 | 1 | 1 | ||
1 | 1 | 2 | 1 | 0 | |
1 | 2 | 2 | 1 | 1 | |
1 | 3 | 2 | 1 | 0 | |
1 | 4 | 2 | 1 | 0 | |
1 | 5 | 2 | 10 | >||
1 | 6 | 2 | 1 | 0 | |
1 | 7 | 2 | 1 | 0 | |
1 | 8 | 2 | 2 | 0 | |
1 | 9 | 2 | 2 | 0 |
不清楚为什么需要再次加入表。
我怀疑以下内容会满足你的需求。由于它没有第二次加入表,所以它只会看到带有Done=1
的行,所以计数是正确的:
SELECT a.ID, COUNT (a.Done) as Count_Done,a.Cycle,a.Week
FROM #Table a
WHERE a.Done=1
GROUP BY a.ID,a.Cycle,a.Week
如果你想包括计数为0的id/cycle/week组合,我建议使用SUM
而不是COUNT
(如果你的done值真的是0/1(:
SELECT a.ID, SUM(a.Done) as Count_Done,a.Cycle,a.Week
FROM #Table a
GROUP BY a.ID,a.Cycle,a.Week
或者
SELECT a.ID, COUNT(CASE WHEN a.Done=1 THEN 1 END) as Count_Done,a.Cycle,a.Week
FROM #Table a
GROUP BY a.ID,a.Cycle,a.Week