选择不同列中具有相同值的行或null。有多个具有相同ID的行

时间:2018-06-25 03:39:55

标签: sql sql-server

我有一个如下表:

enter image description here

我必须删除MS1,MS2,MS3,MS4和MS5中具有不同值的id。NuLL值未检查。我的最终o / p应该与MS1,MS2,MS3,MS4和MS5中的值相同。

我的操作如下:

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以找到不匹配的ID:

select id
from t
group by id
having min(ms1) <> max(ms1) or
       min(ms2) <> max(ms2) or
       min(ms3) <> max(ms3) or
       min(ms4) <> max(ms4) or
       min(ms5) <> max(ms5) ;

您可以通过其他方式获取其余ID,例如说left join

select t.*
from t left join
     (select id
      from t
      group by id
      having min(ms1) <> max(ms1) or
             min(ms2) <> max(ms2) or
             min(ms3) <> max(ms3) or
             min(ms4) <> max(ms4) or
             min(ms5) <> max(ms5) 
     ) ids
     on t.id = ids.id
where ids.id is null;

答案 1 :(得分:0)

 select outerInstance.* from t outerInstance where outerInstance.id not in 
   (select innerInstance.id from t innerInstance where
    isnull(innerInstance.ms1,'null') not in (isnull(innerInstance.ms2,innerInstance.ms1),'null') or
    isnull(innerInstance.ms1,'null') not in (isnull(innerInstance.ms3,innerInstance.ms1),'null') or
    isnull(innerInstance.ms1,'null') not in (isnull(innerInstance.ms4,innerInstance.ms1),'null') or
    isnull(innerInstance.ms1,'null') not in (isnull(innerInstance.ms5,innerInstance.ms1),'null') or 
    isnull(innerInstance.ms2,'null') not in (isnull(innerInstance.ms3,innerInstance.ms2),'null') or
    isnull(innerInstance.ms2,'null') not in (isnull(innerInstance.ms4,innerInstance.ms2),'null') or
    isnull(innerInstance.ms2,'null') not in (isnull(innerInstance.ms5,innerInstance.ms2),'null') or
    isnull(innerInstance.ms3,'null') not in (isnull(innerInstance.ms4,innerInstance.ms3),'null') or
    isnull(innerInstance.ms3,'null') not in (isnull(innerInstance.ms5,innerInstance.ms3),'null') or
    isnull(innerInstance.ms4,'null') not in (isnull(innerInstance.ms5,innerInstance.ms4),'null')) ;

尽管我从未使用过SQL Server,但是请尝试一下。它可能对您有帮助