mysql - 如何按一列在表中创建子表?
问题描述
我一直在做 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),那么,
- 对于日期 > , IN - FUTURE
- 对于日期 < ,已交付
- 对于 max(date) < ,交付。
- 从所有小于当前日期的日期中,应将其中的最大(最新)标记为交付。(只有一个会在那里)。例如,如果今天的日期是 2021 年 8 月 8 日,并且在数据库中我们有 07-08-2021、06-08-2021 和 05-08-2021 等日期,那么 07-08-2021 应标记为交付,但其余两个应标记为已交付。
但这是针对每个员工 ID 分别完成的。此外,如果这可以仅使用查询而不使用脚本来完成,那将更可取。我们还可以添加新的 EMP_ID。
请指导。谢谢你。
解决方案
- 我从状态不在未来的日期中选择最大值
- 然后比较我们是否有一个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
推荐阅读
- c# - 警告“字段 .... 从未分配给并且将始终具有其默认值 null”
- webpack - Webpack 5:如何允许 setImmediate?
- javascript - 算法的时间复杂度 - JavaScript
- php - 抽象工厂无法创建 magentoframeworkappdeploymentconfig 的实例(别名:Magento\Framework\App\DeploymentConfig)
- c++ - 如何按 shared_ptr 包含的索引比较两个向量索引
- r - 与 ifelse 语句一起应用,并且 is.na 不是“求和”而是输出矩阵 - 我的逻辑错误在哪里?
- android - 在 Android 4.2 上运行谷歌云语音 api
- c# - 使用 c# 替换字符串中的许多字符
- bash - jenkins bash 脚本 - 从查找命令结果中删除目录路径
- python - 使用startswith() 但不包含指定元素