基于多个行更新列值

问题描述 投票:0回答:1

我有一张桌子,例如:

 col1 | col2 | col3 
____________________
 abc  |  xyz |  0
 abc  |  xyz |  1
 abc  |  xyz |  0
 abc  |  xyz |  0

我想从表中选择除col3之外的与众不同的表,如果col3的值不同,则将col3的值更新为0。(如果所有col3的值相同,那么distinct将返回不同的行)。

我期望这里的输出是:

 col1 | col2 | col3 
____________________
 abc  |  xyz |  0

有帮助吗?

sql sql-server distinct
1个回答
0
投票

这是您想要的吗?

select distinct col1, col2, 0 as col3
from t;

或者也许:

select col1, col2, 0 as col3
from t
group by col1, col2
having min(col3) <> max(col3)
union all
select col1, col2, col3
from t
where not exists (select 1
                  from t
                  where t2.col1 = t.col1 and t2.col2 = t.col2 and
                        t2.col3 <> t.col3
                 );
© www.soinside.com 2019 - 2024. All rights reserved.