我有一张任务表。一个活动可能有许多具有不同状态的任务。我需要在主活动视图中添加列,以显示打开的任务数、关闭的任务数和总任务数。我想我应该创建一个视图,将每个活动的总数分组,然后通过activityid加入。我无法使用正确的数字创建视图,请帮助。这不会返回正确的数字:
等同于“opentasks”的状态值为0、1和3“closedtasks”为3
现有表-任务
ID | WorkID| Status
1 | 5 | 2
2 | 5 | 2
3 | 5 | 0
4 | 5 | 3
5 | 6 | 2
6 | 7 | 0
7 | 7 | 0
8 | 9 | 1
9 | 9 | 2
我需要的结果视图是:
WorkID | OpenTasks | ClosedTasks | TotalTasks
5 | 2 | 2 | 4
6 | 0 | 1 | 1
7 | 2 | 0 | 2
9 | 1 | 1 | 2
SELECT top 10000 WorkActivityId,
COUNT(CASE WHEN status = 2 then 1 ELSE NULL END) as "ClosedTasks",
COUNT(CASE WHEN status <> 2 then 1 ELSE NULL END) as "OpenTasks",
COUNT(CASE WHEN status < 10 then 1 ELSE NULL END) as "TotalTasks"
FROM [SDMTWorkActivity].[WorkActivity].[Tasks]
GROUP BY WorkActivityId order by WorkActivityId
我没有sql那么好,所以谢谢你的建议谢谢
1条答案
按热度按时间vwkv1x7d1#
您的查询应该可以工作,但是您可以使用
sum
```SELECT
WorkId,
SUM(CASE WHEN status <> 2 then 1 ELSE 0 END) as "OpenTasks",
SUM(CASE WHEN status = 2 then 1 ELSE 0 END) as "ClosedTasks",
SUM(CASE WHEN status < 10 then 1 ELSE 0 END) as "TotalTasks"
FROM [SDMTWorkActivity].[WorkActivity].[Tasks]
GROUP BY WorkId
order by WorkId