SQL 不同的多列
SQL distinct multiple columns
我有一个 table 如下:
book_id author_id mark year
1 1 BAD 2014
1 1 MEDIUM 2014
1 1 GREAT 2015
我想执行一个查询,为每个作者提供最好的书。
像这样:
book_id author_id mark year
1 1 GREAT 2015
我尝试在多个字段上使用 distinct 关键字 - 但是当我这样做时:
select distinct book_id, author_id from Books
我只得到 book_id 和 author_id(正如预期的那样)——但我还需要标记和年份——但我无法将其添加到不同的短语中。
目前我正在使用 Postgres 9.4,但我需要一个 ANSI-SQL 解决方案。
有什么办法可以做到吗?
greatest-n-per-group 问题通常使用 window 函数解决:
select *
from (
select book_id, author_id, mark, year,
row_number() over (partition by author_id order by case mark when 'GREAT' then 1 when 'MEDIUM' then 2 else 3 end) as rn
from books
) t
where rn = 1;
以上是标准 ANSI SQL,但在 Postgres 中使用(专有)distinct on
通常要快得多:
select distinct on (author_id) book_id, author_id, mark, year,
from books
order by author_id,
case mark when 'GREAT' then 1 when 'MEDIUM' then 2 else 3 end
我有一个 table 如下:
book_id author_id mark year
1 1 BAD 2014
1 1 MEDIUM 2014
1 1 GREAT 2015
我想执行一个查询,为每个作者提供最好的书。 像这样:
book_id author_id mark year
1 1 GREAT 2015
我尝试在多个字段上使用 distinct 关键字 - 但是当我这样做时:
select distinct book_id, author_id from Books
我只得到 book_id 和 author_id(正如预期的那样)——但我还需要标记和年份——但我无法将其添加到不同的短语中。
目前我正在使用 Postgres 9.4,但我需要一个 ANSI-SQL 解决方案。
有什么办法可以做到吗?
greatest-n-per-group 问题通常使用 window 函数解决:
select *
from (
select book_id, author_id, mark, year,
row_number() over (partition by author_id order by case mark when 'GREAT' then 1 when 'MEDIUM' then 2 else 3 end) as rn
from books
) t
where rn = 1;
以上是标准 ANSI SQL,但在 Postgres 中使用(专有)distinct on
通常要快得多:
select distinct on (author_id) book_id, author_id, mark, year,
from books
order by author_id,
case mark when 'GREAT' then 1 when 'MEDIUM' then 2 else 3 end