根据多列检查选择唯一记录

时间:2017-03-14 15:54:07

标签: sql postgresql

我有一个postgres表fetches,其中包含以下列

id  |  status  |  company_id  |  created_at
-------------------------------------------
10  |  success |  2773        |  2017-03-14
11  |  error   |  190         |  2017-03-02
12  |  error   |  303         |  2017-03-01
13  |  error   |  286         |  2017-02-16
14  |  error   |  2773        |  2016-12-05

我试图达到以下结果:

id  |  status  |  company_id  |  created_at
-------------------------------------------
11  |  error   |  190         |  2017-03-02
12  |  error   |  303         |  2017-03-01
13  |  error   |  286         |  2017-02-16

这是我试图应用的逻辑:

  1. 获取状态为error的所有提取。
  2. 如果结果中包含company_id fetch,最新的created_atsuccess}为company_id = 2773,则将其从最终结果集中跳过。
  3. success将被跳过,因为它的最新获取状态为select [ExtraDimension].[ExtraHierarchy].[ExtraLevel].[All] on 0, [Calendar].[Year].[Year].Member * {[Measures].[ValueA],[Measures.ValueB],[Measures.ValueC]} on 1 from [MyCube]
  4. 请告知我如何以SQL方式完成此任务。

3 个答案:

答案 0 :(得分:1)

尝试外连接:

with succ as (select company_id from fetches where status = 'success')
select fetches.* 
from fetches
left outer join succ on succ.company_id = fetches.company_id
where succ.company_id is null;

答案 1 :(得分:1)

您可以使用窗口函数:

select f.*
from (select f.*,
             sum( (status = 'success')::int) over (partition by company_id) as isSuccess
      fetches f
     ) f
where isSuccess = 0 and status = 'error';

答案 2 :(得分:0)

似乎你需要公司的行没有成功的状态

select * from my_table 
where company_id not in (select company_id from my_table where status = 'success')
相关问题