sql - 需要查询以下逻辑以在表中添加新列
问题描述
- 如果 PersonID 联系人 [TYPE] = "owner" 并在同一天为该 persinID 以相同 [TYPE] = "owner" 结尾,则输出为 Y
- 第一个联系人的个人 ID 将是 [TYPE] = "owner" 和 [TITLE] = "Authentication"
- 如果 personID 以 [TYPE] = "owner" 开头,并在同一天以该 persinID 的其他类型结束,则输出 N
- 如果 personID 在特定日期没有 [TYPE] = "owner" 则输出为 NUll
下面是示例数据,预期输出在预期结果列中
请让我知道如何实现它
我试过了,但我无法得到预期的结果
ID | 类型 | 标题 | 日期 | 个人ID | 预期成绩 |
---|---|---|---|---|---|
3656 | 所有者 | 验证 | 2020 年 8 月 17 日 | 5538 | ñ |
3688 | 所有者 | 地位 | 2020 年 8 月 17 日 | 5538 | ñ |
4536 | 称呼 | 信息 | 2020 年 8 月 17 日 | 5538 | ñ |
4366 | 所有者 | 验证 | 2020 年 8 月 17 日 | 6838 | 是 |
4379 | 所有者 | 地位 | 2020 年 8 月 17 日 | 6838 | 是 |
4554 | 所有者 | S 状态 | 2020 年 8 月 17 日 | 6838 | 是 |
4494 | 所有者 | 验证 | 2020 年 9 月 27 日 | 3666 | ñ |
4503 | 所有者 | 地位 | 2020 年 9 月 27 日 | 3666 | ñ |
4731 | 回答 | 称呼 | 2020 年 9 月 27 日 | 3666 | ñ |
5030 | 回答 | 信息 | 2020 年 9 月 27 日 | 3666 | ñ |
8642 | 所有者 | 验证 | 2020 年 9 月 27 日 | 3666 | 是 |
2635 | 所有者 | 验证 | 2020 年 9 月 27 日 | 5981 | 是 |
2640 | 所有者 | 地位 | 2020 年 9 月 27 日 | 5981 | 是 |
1234 | 项目 | 私人的 | 2020 年 10 月 22 日 | 9989 | 无效的 |
1235 | 差距 | 落后 | 2020 年 10 月 22 日 | 9989 | 无效的 |
1236 | 失利 | 失利 | 2020 年 10 月 22 日 | 9989 | 无效的 |
1237 | 称呼 | 地位 | 2020 年 10 月 22 日 | 9989 | 无效的 |
解决方案
您可以使用窗口函数,假设排序基于id
- 特别是first_value()
.
您对返回值的描述不完整。但想法是:
select t.*,
(case when first_type = 'OWNER' and first_type = last_type
then 'Y'
when first_type = 'OWNER' and first_title = 'AUTHENTICATION'
then ? -- not specified in question
when first_type = 'OWNER'
then 'N'
when sum(case when type = 'OWNER' then 1 else 0 end) over (partition by personid, date) = 0
then NULL
else ? -- other cases not specified
end) as expected_results
from (select t.*,
first_value(type) over (partition by personid, date order by id) as first_type,
first_value(title) over (partition by personid, date order by id) as first_title,
first_value(type) over (partition by personid, date order by id desc) as last_type
from t
) t
推荐阅读
- java - PDFBox:突出显示文本
- python - 如何查找列表中特定元组的元素总和?
- sql - 仓库活动记录总值
- python - Django - 初始表单字段值未显示
- python - 如何在 python 中使用 Gurobi 的 MIPGap 和 TimeLimit?
- python - 如何获得 2 个不同的 django 模型字段的差异?
- data-structures - 使用链表尝试复杂度
- python - 使用 Singularity 容器解释器的 Python 代码完成 IntelliSense
- ios - Apple 钱包通行证更新通知悄无声息地传递,没有通知横幅
- regex - 如何使正则表达式在找到每个匹配项时不消耗文本?