希望我可以正确地阐明这一点。我在“风险与控制”数据库中有3个表。
表1包含所有风险及其发生可能性的详细信息。风险ID是唯一值:
Risk ID |Risk Desc |Impact | Likelihood
4363 | XXX | High | Likely
2357 | XXX | Low | Unlikely
7629 | XXX | Medium | Unlikely
1929 | XXX | Low | Likely
表2包含所有对照的详细信息以及其有效性的等级。控件ID是唯一值:
Control ID | Control Rating
4566 | Effective
1431 | Not Effective
6724 | Effective
3415 | Effective
表3包含了风险及其“多对多关系”中的链接控件的映射,即风险可以链接到多个控件,反之亦然。
Risk ID | Control |
4363 | 4566 |
4363 | 1431 |
2357 | 4566 |
7629 | 6724 |
我正在尝试通过3个计数列创建所有风险的视图以及其控制有效性的汇总视图。一种计算链接的控件的总数,一种计算有效的控件的总数,另一种计算无效的控件的总数。
输出看起来像这样:
Risk ID |Risk Desc |Impact | Likelihood | Controls | Effective | Not Effective
4363 | XXX | High | Likely | 2 | 1 | 1
2357 | XXX | Low | Unlikely | 1 | 1 | 0
7629 | XXX | Medium | Unlikely | 1 | 1 | 0
1929 | XXX | Low | Likely | 1 | 0 | 1
我设法获得了第一部分,但是不确定如何添加其他计数吗?
SELECT Table_1.RISK_ID,
Table_1.RISK_DESC,
Table_1.Impact,
Table_1.Likelihood,
COUNT(TABLE_2.CONTROL_ID) AS Total_Controls
FROM Table_1
INNER JOIN Table_2
ON Table_1.RISK_ID = Table_2.RISK_ID
GROUP BY Table_1.RISK_ID,
Table_1.RISK_DESC,
Table_1.Impact,
Table_1.Likelihood
任何帮助都将不胜感激。
答案 0 :(得分:0)
您可以对“有效”和“无效”列使用简单的数学和聚合。伪代码:
控件= COUNT(*)
有效= SUM(在Control_Rating =“ Effective” THEN 1 ELSE 0 END的情况下出现)
无效= SUM(在Control_Rating =“无效”的情况下,然后1否则0结束)
答案 1 :(得分:0)
我不确定这是否正确。在示例表中,表2中没有任何风险ID,但示例显示您在Risk_id上联接表1和表2?因此,假设您的样本表正确,我就写这个。
SELECT Table_1.RISK_ID,
Table_1.RISK_DESC,
Table_1.Impact,
Table_1.Likelihood,
COUNT(TABLE_2.CONTROL_ID) AS Total_Controls,
COUNT(CASE WHEN CONTROL_RATING IN ('Effective') THEN 'x' END) as effective,
COUNT(CASE WHEN CONTROL_RATING IN ('Not Effective') THEN 'x' END) as not_effective
FROM Table_1
INNER JOIN Table_3
ON Table_3.Risk_ID = Table_1.Risk_ID
INNER JOIN Table_2
ON Table_2.CONTROL_ID = Table_3.CONTROL
GROUP BY Table_1.RISK_ID,
Table_1.RISK_DESC,
Table_1.Impact,
Table_1.Likelihood
总和也可以使用,但是您想要COUNT()