sql - 将同一列中的值与 SQL Server 中的其他列进行比较
问题描述
我有一张如下表
id ParentName HandleName CreatedDate
===================================================
139 MI MI-Chart-QL 2018-02-20
139 MI MI-chart-act 2018-02-20
139 MI MI-chart-act 2018-02-20
139 CRA CRA-chart-act 2018-02-20
139 CRA CRA-Chart-act 2018-02-20
我想添加一个带有值的列 - 如果带有Act的 HandleName 具有与具有QL的 id、CreatedDate 和 ParentName 的 HandleName 相同的 id、CreatedDate 和 ParentName ,那么它是有意或无意的。我正在寻找的决赛桌是
id ParentName HandleName CreatedDate Intentionally/unintentionally
====================================================================================
139 MI MI-Chart-QL 2018-02-20 Intentionally
139 MI MI-chart-act 2018-02-20 Intentionally
139 MI MI-chart-act 2018-02-20 Intentionally
139 CRA CRA-chart-act 2018-02-20 Unintentionally
139 CRA CRA-Chart-act 2018-02-20 Unintentionally
带有“CRA-chart-act”的 HandleName 是无意的,因为 ParentName 与“MI-Chart-QL”不匹配
我使用了下面的代码(如果 Row_Number()>2 我可以故意标记它们)但是我如何检查它们的父名称是否相同以有意或无意地标记它们?
Row_Number() over (Partition by id, CreatedDate ORDER BY createdDate asc)
解决方案
您可以使用窗口函数:
select t.*,
case when max(case when handlename like '%-QL%' then 1 else 0 end)
over(partition by id, parentname, createddate) = 1
then 'Intentionally'
else 'Unintentionally'
end as status
from mytable t
推荐阅读
- hibernate-spatial - 如何在休眠空间中使用 PostgisFunctions 来转换 CRS 几何
- java - Java:访问修饰符的标准实践
- git - 如何将 Git Master 分支的更改合并到子分支中?( Git 分支策略)
- javascript - 不能再在模拟器上运行 React Native 项目了
- php - 如何用 preg_replace 替换完全匹配?
- java - 给定 x,y 点列表的不规则多边形内的随机 x,y 坐标,而不在这样的角点或边缘上
- amazon-s3 - 如何在 S3 上上传临时文件
- reactjs - Redux , state.concat 不是 rootReducer 的函数。并被迫重新渲染一个元素以查看状态变化
- bash - 使用 Bash 获取在子 shell 中启动的 Python 脚本的退出代码
- python - Telegram API (ModuleNotFoundError: No module named 'telethon.errors.rpc_errors_401')