首页 > 解决方案 > 如何按一列在表中创建子表?

问题描述

我一直在做 SQL,我被困在一个点上。例如,假设我们有一个表 Employee,其中包含 Emp_ID(varchar)、DELIVERY_TIME(date)、Delivery_number(Varchar) 列

EMP_ID 交货时间 DELIVERY_NUMBER
E01 21-08-2021 4
E01 21-08-2019 1
E01 21-08-2022 5
E01 21-05-2021 2
E01 07-08-2021 3
E02 21-08-2021 4
E02 21-08-2023 5
E02 21-08-2020 1
E02 21-06-2021 2
E02 06-08-2021 3

现在我想通过一些查询在其中添加一个状态列来操作表,例如:

EMP_ID 交货时间 地位
E01 21-08-2021 在未来
E01 21-08-2019 发表
E01 21-08-2022 在未来
E01 21-05-2021 发表
E01 07-08-2021 交付
E02 26-08-2021 在未来
E02 21-08-2023 在未来
E02 21-08-2020 发表
E02 21-06-2021 发表
E02 06-08-2021 交付

基本上,如果今天的日期是 2021 年 9 月 8 日 (08-08-2021),那么,

但这是针对每个员工 ID 分别完成的。此外,如果这可以仅使用查询而不使用脚本来完成,那将更可取。我们还可以添加新的 EMP_ID。

请指导。谢谢你。

标签: mysqlsqldatabasemysql-workbenchrdbms

解决方案


  • 我从状态不在未来的日期中选择最大值
  • 然后比较我们是否有一个delivery_time,即等于上面点的最大日期。如果是,那么它正在交付。
with data as (

select 
*,
case when when curdate() < delivery_time then 'In future'
     when  curdate() > delivery_time then 'delivered'
else 'not categorized'
END as status

from [table name]
),

max_date as (
select 
*,
max(case when status not in ('In future') then delivery_time else null end) 
    over(partition by emp_id order by delivery_time desc) as max_delivery_time_when_not_in_future

from data
)

select 
emp_id,
delivery_time,
case 
   when max_delivery_time_when_not_in_future = delivery_time 
   then 'delivering'  else status end as final_status
from max_date

推荐阅读