如何返回0(而不是NULL)的count(*)

时间:2011-11-07 04:35:55

标签: sql sql-server tsql aggregate-functions

我有这段代码:

SELECT Project, Financial_Year, COUNT(*) AS HighRiskCount
INTO #HighRisk 
FROM #TempRisk1
WHERE Risk_1 = 3
GROUP BY Project, Financial_Year

当计数为零时,它不会返回任何行。如何在HighRiskCount设置为0的情况下显示这些行?

7 个答案:

答案 0 :(得分:9)

当行数为0时,您无法从表中选择值。在哪里可以获取不存在的行的值?

要执行此操作,您必须拥有另一个表格,用于定义有效ProjectFinancial_Year值的列表。然后,您将从此表中选择,在现有表格上执行left join,然后进行分组。

这样的事情:

SELECT l.Project, l.Financial_Year, COUNT(t.Project) AS HighRiskCount
INTO #HighRisk 
FROM MasterRiskList l
left join #TempRisk1 t on t.Project = l.Project and t.Financial_Year = l.Financial_Year
WHERE t.Risk_1 = 3
GROUP BY l.Project, l.Financial_Year

答案 1 :(得分:4)

将您的SELECT个问题换成ISNULL

SELECT ISNULL((SELECT Project, Financial_Year, COUNT(*) AS hrc
INTO #HighRisk 
FROM #TempRisk1
WHERE Risk_1 = 3
GROUP BY Project, Financial_Year),0) AS HighRiskCount

如果您的SELECT返回一个号码,它就会通过。如果它返回NULL,则0将通过。

答案 2 :(得分:2)

假设您有'Project'和'Financial_Year',其中Risk_1不同于3,那些就是您打算包含的那些。

SELECT Project, Financial_Year, SUM(CASE WHEN RISK_1 = 3 THEN 1 ELSE 0 END) AS HighRiskCount
INTO #HighRisk 
FROM #TempRisk1
GROUP BY Project, Financial_Year

注意我删除了where部分。

顺便说一句,你当前的查询没有返回null,它没有返回任何行。

答案 3 :(得分:1)

使用:

   SELECT x.Project, x.financial_Year, 
          COUNT(y.*) AS HighRiskCount
     INTO #HighRisk 
     FROM (SELECT DISTINCT t.project, t.financial_year
             FROM #TempRisk1
            WHERE t.Risk_1 = 3) x
LEFT JOIN #TempRisk1 y ON y.project = x.project
                      AND y.financial_year = x.financial_year
 GROUP BY x.Project, x.Financial_Year

获得零计数的唯一方法是对要查看零计数的不同值列表使用OUTER联接。

答案 4 :(得分:0)

SQL通常在返回表中的值时出现问题。要完成此任务(无论如何不使用存储过程),您将需要另一个包含缺失值的表。

假设每个项目/财务年度组合需要一行,您需要一个包含每个有效Project,Finanical_Year组合的表:

 SELECT HR.Project, HR.Financial_Year, COUNT(HR.Risk_1) AS HighRiskCount
 INTO #HighRisk HR RIGHT OUTER JOIN ProjectYears PY
   ON HR.Project = PY.Project AND HR.Financial_Year = PY.Financial_Year
 FROM #TempRisk1
 WHERE Risk_1 = 3
 GROUP BY HR.Project, HR.Financial_Year

请注意,我们正在利用这样的事实:COUNT()只计算非NULL值,以获得仅由新ProjectYears表中的数据组成的结果集记录的0 COUNT结果。

或者,您可能每个项目只能返回一个0计数记录(或者每个financial_year可能会返回一个)。您可以修改上述解决方案,以便JOINed表只有一列。

答案 5 :(得分:0)

稍长一点,但作为解决方案呢?

IF EXISTS (
        SELECT *
        FROM #TempRisk1
        WHERE Risk_1 = 3
    )
    BEGIN
        SELECT Project, Financial_Year, COUNT(*) AS HighRiskCount
        INTO #HighRisk 
        FROM #TempRisk1
        WHERE Risk_1 = 3
        GROUP BY Project, Financial_Year
    END
ELSE
    BEGIN
        INSERT INTO #HighRisk 
            SELECT 'Project', 'Financial_Year', 0
    END

答案 6 :(得分:-2)

MSDN - ISNULL function


SELECT Project, Financial_Year, ISNULL(COUNT(*), 0) AS HighRiskCount
INTO #HighRisk 
FROM #TempRisk1
WHERE Risk_1 = 3
GROUP BY Project, Financial_Year