COUNT 和 GROUP BY 几列
COUNT and GROUP BY several columns
我得到了 table 像这样我想计算“WeekCount”以便计算“完成”的数量但按周期和一周分组。
|
ID
Day
Cycle
Week
Done
1
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
1
0
1
6
2
1
0
1
7
2
1
0
1
8
2
2
0
1
9
2
2
0
我试过这样的事情:
SELECT a.ID, COUNT (a.Done) as Count_Done,a.Cycle,a.Week
FROM #Table a
JOIN #Table b ON a.ID=b.ID AND a.Cycle=b.Cycle AND a.Week=b.Week
WHERE a.Done=1
GROUP BY a.ID,a.Cycle,a.Week
但我正在计算所有行数,而不仅仅是那些“完成=1”的行数
像这样:
ID
Count_Done
Cycle
Week
1
1
1
1
1
7
2
1
虽然我期待这样的结果:
ID
Count_Done
Cycle
Week
1
1
1
1
1
1
2
1
感谢您的帮助!
不清楚您为什么需要第二次加入 table。
我怀疑以下内容可以满足您的需求。由于它没有第二次加入 table,它只会看到带有 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
(如果你的完成值确实是 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
我得到了 table 像这样我想计算“WeekCount”以便计算“完成”的数量但按周期和一周分组。 |
ID | Day | Cycle | Week | Done |
---|---|---|---|---|
1 | 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 | 1 | 0 |
1 | 6 | 2 | 1 | 0 |
1 | 7 | 2 | 1 | 0 |
1 | 8 | 2 | 2 | 0 |
1 | 9 | 2 | 2 | 0 |
我试过这样的事情:
SELECT a.ID, COUNT (a.Done) as Count_Done,a.Cycle,a.Week
FROM #Table a
JOIN #Table b ON a.ID=b.ID AND a.Cycle=b.Cycle AND a.Week=b.Week
WHERE a.Done=1
GROUP BY a.ID,a.Cycle,a.Week
但我正在计算所有行数,而不仅仅是那些“完成=1”的行数 像这样:
ID | Count_Done | Cycle | Week |
---|---|---|---|
1 | 1 | 1 | 1 |
1 | 7 | 2 | 1 |
虽然我期待这样的结果:
ID | Count_Done | Cycle | Week |
---|---|---|---|
1 | 1 | 1 | 1 |
1 | 1 | 2 | 1 |
感谢您的帮助!
不清楚您为什么需要第二次加入 table。
我怀疑以下内容可以满足您的需求。由于它没有第二次加入 table,它只会看到带有 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
(如果你的完成值确实是 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