我是SQL新手,面临分组汇总数据的问题。 考虑一下:
PR_ProjectName CategoryName Compliant AssessmentID ComplianceRAG
CUNA policy compliance Yes 1 Green
CUNA policy compliance Yes 2 Green
CUNA policy compliance Yes 3 Green
CUNA policy compliance No 4 Red
CUNA Inventory Yes 5 Red
CUNA Security No 6 Red
CUNA Security Yes 7 Green
CUNA Security No 8 Red
CUNA Security Yes 9 Green
最后一列应该向我发送累计数据,如果某个特定类别的合规性为No,它将向我发送RED,用于ComplainceRAG中的所有列。所有4行政策抱怨的示例'因为RED中的至少1列,它必须返回RED。对于'库存'它应该是绿色的。
以下是我当前的查询:(请指导我CASE声明需要修改的内容):
SELECT PDD.PR_ProjectName, IC.CategoryName, IA.Compliant, IA.AssessmentID,
CASE
WHEN IA.Compliant = 'Yes' THEN 'Green'
WHEN IA.Compliant = 'No' THEN 'Red'
END as ComplianceRAG
FROM InfoSecAssessment IA
INNER JOIN InfoSecConduct ICon ON Icon.ConductID = IA.ConductID
INNER JOIN PROJECT_DIM_DM PDD ON PDD.PR_ProjectId = Icon.ProjectID
INNER JOIN InfoSecQuestionMaster IQ ON IA.QuestionID = IQ.QuestionID
INNER JOIN InfoSecControlCategoryMaster IC ON IC.CategoryID = IQ.CategoryID
WHERE AssessmentSubmitted = 1 AND
PDD.pr_isActive=1 and PDD.PR_EFF_END_DATE='31Dec3000'
GROUP BY IC.CategoryName, PDD.PR_ProjectName, IA.AssessmentID, IA.Compliant
答案 0 :(得分:2)
将以下左连接添加到所有类别的派生表中,且至少有1'否'。
LEFT JOIN (
SELECT DISTINCT IC.CategoryName
FROM InfoSecControlCategoryMaster IC
JOIN InfoSecQuestionMaster IQ ON IC.CategoryID = IQ.CategoryID
JOIN InfoSecAssessment IA ON IA.QuestionID = IQ.QuestionID
WHERE IA.Compliant = 'No'
) red ON red.CategoryName = IC.CategoryName
然后更改您的case语句以检查类别是否在派生表中
CASE WHEN red.CategoryName IS NULL
THEN 'Green' ELSE 'Red'
END AS ComplianceRAG
答案 1 :(得分:1)
我在这里制作了一个简化的SQL小提琴:http://sqlfiddle.com/#!2/16eba/15/2
希望有所帮助!