计算两列之和

时间:2019-04-08 20:02:19

标签: sql postgresql

我正在尝试从一个结果子集中计算2列的总和,到目前为止,我已经将它们加在一起

SELECT COUNT(*) 
FROM table_name 
WHERE column_1 + column_2 >= 3 IN (SELECT id 
                                   FROM table_name 
                                   where id = 16 
                                   AND (name = 'Richard') 
                                   ORDER BY column_3 
                                   DESC LIMIT 10);

我期望输出的是总数为>=3的情况数,例如5

此刻我得到了错误

ERROR: operator does not exist: integer >= boolean

我觉得我走错了路。我该如何构造此查询

1 个答案:

答案 0 :(得分:1)

您没有为IN语句提供值,该语句返回一个布尔值,说明值是否在SELECT语句的结果之内

要使查询正常运行,最简单的更改是:

SELECT COUNT(*) FROM table_name 
WHERE column_1 + column_2 >= 3 
AND id IN(
  SELECT id FROM table_name 
  WHERE id = 16 AND (name = 'Richard')
  ORDER BY column_3 DESC LIMIT 10
);

但是,如果table_name实际上被两次使用,正确的方法是:

SELECT COUNT(*) FROM table_name
WHERE id = 16 AND (name = 'Richard')
AND column_1 + column_2 >= 3
ORDER BY column_3 DESC LIMIT 10;