SQL查询为PercentAnalysed提供了不同的结果

时间:2015-04-17 06:04:57

标签: mysql sql database

以下是我的疑问:

SELECT Runs.runId
    ,Runs.prodId
    ,passCount
    ,failCount
    ,CASE 
        WHEN failcount <> 0
            THEN cast((round(((counts.Count 100.0) / failcount), 0)) AS NUMERIC)
        WHEN failcount = 0
            OR ***counts.Count IS NULL
            THEN 100***
        ELSE 0
        END **PercentAnalysed**
FROM Runs AS Runs
INNER JOIN Product AS Product
    ON Runs.prodId = Product.prodId
LEFT JOIN (
    SELECT COUNT(*) AS 'Count'
        ,Results.runId
    FROM Results
    INNER JOIN Runs
        ON Results.runId = Runs.runId
    WHERE Analysed = 'True'
    GROUP BY Results.runId
    ) counts
    ON counts.runId = Runs.runId

我的问题是,当counts.Count为NULL时,Percent Analyzed不会显示为100.它是空白的。 (编辑:根据查询,您可以看到当count.Count为NULL时,PercentAnalysed列的值应为100,但显示为NULL)

有人能告诉我为什么CASE声明中的条件WHEN failcount = 0 OR counts.Count IS NULL那么100不起作用?

1 个答案:

答案 0 :(得分:0)

这应该会给你预期的结果:

failcount更改为NULL如果它为零并将NULL作为计算结果更改回100

CAST(COALESCE(ROUND(((counts.COUNT * 100.0) / NULLIF(failcount, 0)), 0), 100) AS NUMERIC)