SQL比较具有相似ID的行中的两个结果

时间:2019-03-29 14:14:56

标签: sql

让我们说我的桌子看起来像这样

id | can_id | last_touch | result
1  | 1001   | 2017-05-01 | good
2  | 1001   | 2017-07-01 | bad
3  | 1002   | 2018-01-01 | good
4  | 1003   | 2019-02-08 | bad

我想创建一个搜索,该搜索将找到行以检查最近的last_touch日期是否为good

如何在搜索中的每个cand_id之间进行“循环”以查找最近的last_touch日期和行的result并返回good的返回值? / p>

2 个答案:

答案 0 :(得分:1)

您可以使用相关子查询:

select t.*,
       (case when result = 'good' then 1 else 0 end) as is_good
from t
where t.last_touch = (select max(t2.last_touch)
                      from t t2
                      where t2.can_id = t.can_id
                     ) ;

或者,如果只需要last_touch'good'的行,则添加and result ='good'to the where`子句。

很难从您的问题中得知您是否需要标志或过滤器。

答案 1 :(得分:1)

您想要相关的子查询:

select t.*, 
       (case when t.result = 'good' then 'yes' else 'no' end) as is_good
from table t
where t.last_touch = (select max(t1.last_touch) from table t1 where t1.can_id = t.can_id);

不过,您也可以使用row_number()

select t.*,
       (case when t.result = 'good' then 'yes' else 'no' end) as is_good
from (select t.*,
             row_number() over (partition by t.can_id order by t.last_touch desc) as seq
      from table t
     ) t
where seq = 1;