1

如果没有找到记录,有没有办法修改此查询以在 Grade 列中返回“0”?现在,当什么都没有找到时,我得到一个空白行。

SELECT  COALESCE(Score, 0) AS Score, COALESCE(Grade,0) AS Grade, LAST_UPDATE, '' as  dummy
FROM (
SELECT (CASE ScanName WHEN '%=APP%' THEN '= Network System' END) AS   System, 
(sum(CASE severity WHEN 1 THEN 10 WHEN 2 THEN 9 WHEN 3 THEN 6 WHEN 4 THEN 3    
END)/COUNT(severity )) AS Score,
(sum(CASE severity WHEN 1 THEN 10 WHEN 2 THEN 9 WHEN 3 THEN 6 WHEN 4 THEN 3   
END)/COUNT(severity )) AS Grade, LAST_UPDATE 

FROM missing_internal

WHERE ScanName like '%APP%'

and LAST_UPDATE >= SUBDATE((SELECT MAX(LAST_UPDATE) from missing_internal), INTERVAL 1 day) 
HAVING System IS NOT NULL  
LIMIT 1

UNION ALL 

SELECT NULL AS Score, NULL AS Grade, 0 AS LAST_UPDATE, '' as dummy

ORDER BY LAST_UPDATE DESC

)  as T2
LIMIT 1;

分数和成绩的目的是相同的,因为我使用单独的脚本将字母成绩应用于分数。

4

2 回答 2

1

看看COALESCE函数...

如果我很好地理解了您的问题,那么下面的查询应该完全符合您的要求(现在返回行时得到零):

SELECT COALESCE(Score, 0) AS Score, COALESCE(Grade,0) AS Grade, LAST_UPDATE 
FROM (
SELECT (CASE ScanName WHEN 'APP' THEN 'Network System' END) AS System, 
(sum(CASE severity WHEN 1 THEN 10 WHEN 2 THEN 9 WHEN 3 THEN 6 WHEN 4 THEN 3    
END)/COUNT(severity )) AS Score,
(sum(CASE severity WHEN 1 THEN 10 WHEN 2 THEN 9 WHEN 3 THEN 6 WHEN 4 THEN 3   
END)/COUNT(severity )) AS Grade, LAST_UPDATE

FROM missing_internal

WHERE ScanName like '%APP%'

and LAST_UPDATE >= SUBDATE((SELECT MAX(LAST_UPDATE) from missing_internal), INTERVAL 1 day)
HAVING System IS NOT NULL  
LIMIT 1

UNION ALL 

SELECT NULL AS Score, NULL AS Grade, 0 AS LAST_UPDATE 

ORDER BY LAST_UPDATE DESC
) AS T2
LIMIT 1;

我还没有测试过查询,所以你可能需要安排它......但是采取这个想法......

如果您只想在列返回空结果时获得零,您可以按照与上面示例相同的方式使用COALESCE :

COALESCE(sum(CASE severity WHEN 1 THEN 10 WHEN 2 THEN 9 WHEN 3 THEN 6 WHEN 4 THEN 3   
END)/COUNT(severity ), 0) AS Grade
于 2012-07-09T21:31:50.850 回答
0

添加一个ELSECASE

(sum(CASE severity 
    WHEN 1 THEN 10 
    WHEN 2 THEN 9 
    WHEN 3 THEN 6 
    WHEN 4 THEN 3 
    ELSE 0
END)/COUNT(severity )) AS Grade

或使用IFNULL()

IFNULL((sum(CASE severity 
        WHEN 1 THEN 10 
        WHEN 2 THEN 9 
        WHEN 3 THEN 6 
        WHEN 4 THEN 3 
        ELSE 0
    END)/COUNT(severity )), 0)  AS Grade
于 2012-07-09T21:31:08.753 回答