首页 > 解决方案 > 需要查询以下逻辑以在表中添加新列

问题描述

下面是示例数据,预期输出在预期结果列中

请让我知道如何实现它

我试过了,但我无法得到预期的结果

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 无效的

标签: sqlsql-servertsql

解决方案


您可以使用窗口函数,假设排序基于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

推荐阅读