检查该人员是否有特定日期的先前记录:db2 sql

zzoitvuj  于 2022-11-07  发布在  DB2
关注(0)|答案(1)|浏览(141)

我有下表:

id      name        start        end 
1       Asla      2021-01-01   2021-12-31
1       Asla      2022-01-01   2022-04-15
2       Tina      2021-05-16   2021-09-23
3       Layla     2021-01-01   2021-09-27
3       Layla     2022-01-01   2022-07-18
2       Sim       2020-05-12   2020-08-13
3       Anderas   2021-07-01   2021-09-13
3       Anderas   2021-10-01   2021-11-18
3       Anderas   2022-01-01   2029-11-18
4       Klara     2022-01-01     null

我想做的是得到在2021年有工作的人(日期),并创建一个显示状态的新列(如果这个人在2022年继续工作--可以,否则不可以,如果这个人是新的,如“Klara”,则得到新的),并显示每个人的最后一条记录。也许太结束=空??????我试过这个。

select w.id ,w.name ,w.start ,w.end, max_date.end 
      from Work_date w
left join (select * from Work_date  where start>='2022-01-01')max_date on max_date.id=id  
     where w.start>='2021-01-01'
``` but the problem i get the result as this 
<pre>
id      name          start        end 
1       Asla         2021-01-01   null
1       Asla         2022-01-01   2022-04-15
2       Tina         2021-05-16   null
3       Layla        2021-01-01   null
3       Layla        2022-01-01   2022-07-18
3       Anderas      2021-07-01   null
3       Anderas      2021-10-01   2021-11-18
3       Anderas      2022-01-01   null
4       Klara        2022-01-01   null
</pre>
men i want to get result as <pre>
id      name        start        end           status
1       Asla       2022-01-01   2022-04-15      ok 
2       Tina       2021-05-16   2021-09-23      not ok
3       Layla      2022-01-01   2022-07-18      ok
3       Anderas    2022-01-01   2029-11-18      ok
4       Klara      2022-01-01     null          ok
f4t66c6m

f4t66c6m1#

看起来你可以简单地聚合。
然后使用CASE WHEN表示状态。

select 
  w.id 
, w.name
, max(w.start) as start
, max(w.end) as end
, case
  when year(max(end)) < 2022 then 'not ok'
  else 'ok'
  end as status
from Work_date w
where w.start >= '2021-01-01'
group by w.id, w.name
order by w.id, max(w.start), max(w.end);

| 识别码|名称|启动|结束|状态|
| - -|- -|- -|- -|- -|
| 一个|阿斯拉|2022年1月1日|2022年4月15日|好的|
| 2个|蒂娜|2021年5月16日|2021年9月23日|不正常|
| 三个|莱拉|2022年1月1日|2022年7月18日|好的|
| 三个|安德拉斯|2022年1月1日|2029年11月18日|好的|
| 四个|克拉拉|2022年1月1日| * 空值 *| 好的|

  • db〈〉fiddle here * 上的演示

相关问题