sql - 如何删除重复的结果

标签 sql postgresql

给定以下架构:

CREATE TABLE IF NOT EXISTS companies (
  id serial,
  name text NOT NULL,

  PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS cars (
  id serial,
  make text NOT NULL,
  year integer NOT NULL,
  company_id INTEGER REFERENCES companies(id),

  PRIMARY KEY (id)
);


INSERT INTO companies (id, name) VALUES
  (1, 'toyota'),
  (2, 'chevy');

INSERT INTO cars (make, year, company_id) VALUES
  ('silverado', 1995, 2),
  ('malibu', 1999, 2),
  ('tacoma', 2017, 1),
  ('custom truck', 2010, null),
  ('van custom', 2005, null);

我如何选择汽车行,只显示给定公司的最新汽车?

例如

select make, companies.name as model, year from cars 
left join companies
on companies.id = cars.company_id
order by make;

输出

     make     | model  | year 
--------------+--------+------
 custom truck |        | 2010
 malibu       | chevy  | 1999
 silverado    | chevy  | 1995
 tacoma       | toyota | 2017
 van custom   |        | 2005

但我只想展示最新的“雪佛兰”,例如

     make     | model  | year 
--------------+--------+------
 custom truck |        | 2010
 malibu       | chevy  | 1999
 tacoma       | toyota | 2017
 van custom   |        | 2005

并且仍然能够按“品牌”排序,并显示没有 null company_id 的汽车。

fiddle 链接: https://www.db-fiddle.com/f/5Vh1sFXvEvnbnUJsCYhCHf/0

最佳答案

SQL可以基于Set Math(离散数学)来完成。因此,您需要所有汽车的集合减去年份小于给定公司 ID 的最大年份的汽车集合。

所有汽车的集合:

select * from cars

年份小于给定公司 ID 的最大年份的所有汽车的集合:

select a.id from cars a, cars b where a.company_id = b.company_id  and a.year < b.year

一组减去另一组:

select * from cars where id not in (select a.id from cars a, cars b where a.company_id = b.company_id  and a.year < b.year)

包含空 company_ids 的结果,因为它们被排除在 id 比较之外:

     make     | model  | year 
--------------+--------+------
 custom truck |        | 2010
 malibu       | chevy  | 1999
 tacoma       | toyota | 2017
 van custom   |        | 2005

关于sql - 如何删除重复的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57121601/

相关文章:

mysql - 如何在不删除现有内容的情况下更新mysql表

sql - 为什么我在 Postgresql psql :/lib64/libpq. so.5 : no version information available (required by psql)? 上不断收到此错误

regex - 选择名称与 PostgreSQL 中的正则表达式匹配的列

java - Hibernate NOT IN 联结表上的子查询

mysql - 外键问题-mysql

sql - Hive - 过滤不在多个范围/区间内的值

SQL - 在不存在的地方插入

sql - Postgres - 获取分配给变量的查询成本

ruby-on-rails - AuthLogic + PostgreSQL 8.4 : persistence_token defined as a string, 然后用作整数

sql - 从 sql 查询 postgres 9.4 创建嵌套的 json