我需要根据以下表生成报告:
CALLS_FOR_PROPOSALS
ID|Name
--+------
1|Call 1
2|Call 2
3|Call 3
PROPOSALS
ID|Call ID|Title
--+-------+----------
1| 1|Proposal 1
2| 2|Proposal 2
3| 2|Proposal 3
PROPOSAL_STATUSES
ID|Proposal ID|Status ID
--+-----------+---------
1| 1| 1
2| 2| 1
3| 3| 1
4| 3| 2
STATUSES
ID|NAME
--+------------
1|Not Reviewed
2|Processing
3|Accepted
4|Rejected
使用此示例数据,有3个提案征集。有三个提案;一个用于呼叫1,两个用于呼叫2.(呼叫3没有任何提议。)每个提议至少分配了一个状态。当一行插入PROPOSALS表时,相应的行将插入到PROPOSAL_STATUSES中,从而使Proposal的初始默认状态为1(未审核)。每次更改状态时,都会在PROPOSAL_STATUSES表中插入一个新行,以便保留状态更改的历史记录。我需要生成一个报告,显示每个呼叫,提交的提案数量,以及具有多个状态的提案数量(即状态已从默认状态更改至少一次。)对于上面的示例数据,结果看起来像这样:
Call Name|Proposals Submitted|Proposals Reviewed|
---------+-------------------+------------------+
Call 1 | 1| 0|
Call 2 | 2| 1|
Call 3 | 0| 0|
如何根据上面的表结构编写SQL查询来生成此报告?谢谢你的帮助。
答案 0 :(得分:1)
类似的东西应该可以解决问题:Demo
SELECT Name as 'Call name',
submitted as 'Proposals Submitted',
SUM(CASE WHEN maxStatus > 1 THEN 1 ELSE 0 END) as 'Proposals Reviewed'
FROM
(SELECT cfp.Name,
sum(case when ps.Status_ID = 1 then 1 else 0 end) as submitted,
MAX(ps.Status_ID) as maxStatus
FROM CALLS_FOR_PROPOSALS cfp
LEFT JOIN PROPOSALS p on cfp.ID = p.CALL_ID
LEFT JOIN PROPOSAL_STATUSES ps on ps.PROPOSAL_ID = p.ID
GROUP BY cfp.Name) AS s
GROUP BY Name, submitted