1

假设您有一个名为 tracker 的表,其中包含以下记录。

issue_id  |  ingest_date         |  verb,status
10         2015-01-24 00:00:00    1,1
10         2015-01-25 00:00:00    2,2
10         2015-01-26 00:00:00    2,3
10         2015-01-27 00:00:00    3,4
11         2015-01-10 00:00:00    1,3
11         2015-01-11 00:00:00    2,4

我需要以下结果

10         2015-01-26 00:00:00    2,3
11         2015-01-11 00:00:00    2,4

我正在尝试这个查询

select * 
from etl_change_fact 
where ingest_date = (select max(ingest_date) 
                     from etl_change_fact);

但是,这只给了我

10    2015-01-26 00:00:00    2,3

这个记录。

但是,我想要所有唯一的记录(change_id)

(a) max(ingest_date) 和

(b) 动词列优先级为(2 - 第一个首选,1 - 第二个首选,3 - 最后一个首选)

因此,我需要以下结果

10    2015-01-26 00:00:00    2,3
11    2015-01-11 00:00:00    2,4

请帮助我有效地查询它。

PS:我不会索引 ingest_date,因为我将在分布式计算设置中将其设置为“分发密钥”。我是数据仓库和查询的新手。

因此,请帮助我以优化方式访问我的 TB 大小的数据库。

4

1 回答 1

1

这是一个典型的“greatest-n-per-group”问题。如果你在这里搜索这个标签,你会得到很多解决方案——包括 MySQL。

对于 Postgres,最快的方法是使用distinct on(这是 SQL 语言的 Postgres 专有扩展)

select distinct on (issue_id) issue_id, ingest_date, verb, status
from etl_change_fact
order by issue_id, 
         case verb 
            when 2 then 1 
            when 1 then 2
            else 3
         end, ingest_date desc;

您可以增强原始查询以使用共同相关的子查询来实现相同的目的:

select f1.* 
from etl_change_fact f1
where f1.ingest_date = (select max(f2.ingest_date) 
                        from etl_change_fact f2
                        where f1.issue_id = f2.issue_id);

编辑

对于过时且不受支持的 Postgres 版本,您可能可以使用以下方法逃脱:

select f1.* 
from etl_change_fact f1
where f1.ingest_date = (select f2.ingest_date
                        from etl_change_fact f2
                        where f1.issue_id = f2.issue_id
                        order by case verb 
                                  when 2 then 1 
                                  when 1 then 2
                                  else 3
                              end, ingest_date desc
                        limit 1);

SQLFiddle 示例:http ://sqlfiddle.com/#!15/3bb05/1

于 2015-02-03T11:50:16.160 回答