首页 > 解决方案 > PostgreSQL 简单查询

问题描述

我的问题是编写一个查询(PostgreSQL)来获得一个“propno”,其中“newsname”不等于“NYT”(答案是 40)。

       newsname       | propno | dateadvert | cost 
----------------------+--------+------------+------
 NYT                  |     30 | 2018-01-01 | 10.2
 NYT                  |     30 | 2018-01-10 | 15.2
 NYT                  |     10 | 2018-01-02 | 20.2
 NYT                  |     20 | 2018-02-01 | 10.2
 Guardian             |     40 | 2018-02-10 |  100
 Guardian             |     10 | 2018-01-02 | 13.2
 Guardian             |     30 | 2018-01-10 | 10.8

感谢帮助

标签: sqlpostgresql

解决方案


您可以使用聚合和having

select propno
from t
group by propno
having count(*) filter (where newsname = 'NYT') = 0;

如果您有一个单独的表,每行一行propno,那么我建议not exists

select p.propno
from props p
where not exists (select 1
                  from t
                  where t.propno = p.propno and
                        t.newname = 'NYT'
                 );

推荐阅读