sql - 合并具有公共(public)字段的同一表的两行

标签 sql sql-server tsql

我正在尝试使用以下条件合并 col1 和 col2 相同的行(这里是最后两行)

-优先行 - “ManualUpdate”列为"is"的行

例如:第 4 列(第 3 列)<>第 5 列(第 3 列),然后第 5 列(第 3 列)

我尝试过使用 'JOIN' 和使用 CASE 语句。但是运气不好 :(

欢迎提出建议。

enter image description here

最佳答案

这很棘手。您希望逐列设置优先级,值有时来自手动更新列,有时来自其他列。

这是一种首先查找手动更新值的方法。如果它不存在,它将取任何值:

select t.col1, t.col2,
       coalesce(max(case when [Manual Update]= 'Yes' then col3 end), max(col3) ) as col3,
       coalesce(max(case when [Manual Update]= 'Yes' then col4 end), max(col4) ) as col4,
       coalesce(max(case when [Manual Update]= 'Yes' then col5 end), max(col5) ) as col5,
       coalesce(max(case when [Manual Update]= 'Yes' then col6 end), max(col6) ) as col6,
       (case when min([Manual Update]) = max([Manual Update]) then min([Manual Update]) end) as [Manual Update]
from table t
group by t.col1, t.col2;

关于sql - 合并具有公共(public)字段的同一表的两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29009144/

相关文章:

c# - 如何将 sql union 转换为 linq

mysql - 在对多个表进行操作的sql语句中使用Or

sql-server - SQL Server 替换功能

sql - 添加当月累积的行

c# - 为什么连字符 (–) 会触发非法 XML 字符错误(C#/SSMS)?

sql - 如何更新 json 对象的键?

sql - 什么时候适合使用index_scan来获取已经排序的数据?

sql - 多用户环境中的临时表使用情况

sql-server - ANSI 相关设置的推荐配置是什么?

tsql - SQLCMD 模式 : Environment variable syntax