Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL跨ID类似的行比较两个结果';s_Sql - Fatal编程技术网

SQL跨ID类似的行比较两个结果';s

SQL跨ID类似的行比较两个结果';s,sql,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 我想创建一个搜索,该搜索将查找行,检查最近的最后一次触摸日期是否为良好 如何在搜索中通过每个cand\u id进行“循环”,以查找最近的最后一次触摸日期

假设我的桌子看起来像这样

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
我想创建一个搜索,该搜索将查找行,检查最近的
最后一次触摸
日期是否为
良好


如何在搜索中通过每个
cand\u id
进行“循环”,以查找最近的
最后一次触摸日期和行的
结果
,并返回if
good

您可以使用相关子查询:

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
                     ) ;
或者,如果您只需要
最后一次触摸
'good'
的行,则将
result='good'
添加到
where`子句中


很难从您的问题中判断您是否需要标志或筛选器。

您可以使用相关子查询:

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
                     ) ;
或者,如果您只需要
最后一次触摸
'good'
的行,则将
result='good'
添加到
where`子句中


很难从您的问题中判断您想要的是标志还是筛选器。

您想要的是相关子查询:

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);
但是,您也可以使用
行编号()

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;

您需要关联子查询:

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);
但是,您也可以使用
行编号()

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;

你能标记正在使用的dbms并显示预期的结果吗?你能标记正在使用的dbms并显示预期的结果吗?事实上,两者都可以。少谈具体答案,多谈我应该研究的内容:-)这很好。谢谢事实上,两种方法都有效。少谈具体答案,多谈我应该研究的内容:-)这很好。非常感谢。