我有2张桌子tblProjects& tblTasks
tblProjects有
ID,PName columns
tbltasks有
ID,PID,TaskDescription,Owner,Status
我正在尝试编写一个查询来获取项目的状态,这些项目会为所有项目提供打开和关闭状态的任务数
输出就像
PName|Open|Closed
我使用了一些子查询和Sum和Groupby,但输出并不像预期的那样。
请专家帮助。
先谢谢。 :)
答案 0 :(得分:0)
我不是专家,但您可以尝试使用条件聚合的以下简单查询:
SELECT t1.ID,
t1.PName,
SUM(CASE WHEN t2.Status = 'open' THEN 1 ELSE 0 END) AS Open,
SUM(CASE WHEN t2.Status = 'closed' THEN 1 ELSE 0 END) AS Closed
FROM tblProjects t1
INNER JOIN tblTasks t2
ON t1.ID = t2.PID
GROUP BY t1.ID,
t1.PName
答案 1 :(得分:-1)
may be this one help
SELECT t1.ID,
t1.PName,
Open=SUM(CASE (t2.Status) WHEN 'open' THEN 1 ELSE 0 END),
Closed=SUM(CASE (t2.Status) WHEN 'closed' THEN 1 ELSE 0 END)
FROM tblProjects t1
INNER JOIN tblTasks t2
ON t1.ID = t2.PID
GROUP BY t1.ID,
t1.PName