如果搜索未找到值,则在sql中添加硬编码行

时间:2017-09-21 16:02:42

标签: sql postgresql

所以我有一个类似这样的表: enter image description here

我选择了......

  SELECT colors,
  COUNT (Num1) AS number1,
 COUNT (Num2) AS number2,
  COUNT (Num3) AS number3,
  COUNT (Num4) AS number4
  From table
  Group By colors

结果将是:

enter image description here

我的问题是: 如果没有显示某些颜色,如何在包含该计数(0 0 0 0)的颜色的结果末尾添加一行? 注意:所有颜色必须显示在结果中,但不是所有颜色都必须写在表

1 个答案:

答案 0 :(得分:1)

您可以将LEFT JOIN用于返回所有可能颜色的子查询:

SELECT s.color, 
      COUNT (t.Num1) AS number1,
      COUNT (t.Num2) AS number2,
      COUNT (t.Num3) AS number3,
      COUNT (t.Num4) AS number4
FROM (-- subquery or table of all possible colors
) s
LEFT JOIN table t
  ON s.color = t.color
GROUP BY s.color;

<强> Rextester Demo

修改

或使用UNION ALL:

WITH cte AS (
    SELECT t.color, 
          COUNT (t.Num1) AS number1,
          COUNT (t.Num2) AS number2,
          COUNT (t.Num3) AS number3,
          COUNT (t.Num4) AS number4
    FROM table t
    GROUP BY t.color
)
SELECT * 
FROM cte
UNION ALL
SELECT color, 0, 0, 0, 0
FROM (--table or subquery) s
WHERE NOT EXISTS (SELECT *
                  FROM cte c
                  WHERE c.color = s.color);

<强> Rextester Demo 2