基于其他行删除行并合并剩余的行

时间:2018-06-15 10:44:06

标签: sql sql-server

我在尝试获取表格以显示我想要的信息时遇到了一些麻烦。我试图让下表只显示第1列或第2列没有真实陈述(1)的ID

IDs     | Column2 | Column3
--------+---------+--------
101     |    0    |    0 
101     |    0    |    1 
102     |    0    |    0
102     |    0    |    0
102     |    0    |    1
103     |    0    |    0
103     |    0    |    0
103     |    0    |    0
104     |    0    |    0
104     |    1    |    0

理想情况下,上表将简化为:

Column1 | Column2 | Column3
--------+---------+--------
103     |    0    |    0 

因为ID 103从不向任何列显示1。不幸的是,我无法绕过逻辑。到目前为止我已经

SELECT DISTINCT
    IDs,
    Column1,
    Column2
FROM Table1
WHERE (Column1 <> 1 AND Column2 <> 1)

但是这也显示了其他ID中没有1的所有行。例如

IDs     | Column2 | Column3
--------+---------+--------
101     |    0    |    0 
102     |    0    |    0
102     |    0    |    0
103     |    0    |    0
103     |    0    |    0
103     |    0    |    0
104     |    0    |    0

当ID中有另一行,其中包含1时,有没有办法删除行,然后根据其ID将其余行合并为单行?

由于 罗布

3 个答案:

答案 0 :(得分:1)

我认为这可以满足您的需求:

select id, max(column2), max(column3)
from t
group by id
having max(column2) = 0 and max(column3) = 0;

答案 1 :(得分:1)

您也可以使用not exists代替:

select distinct t.*
from table t
where not exists (select 1 from table t1 where t1.ids = t.ids and t1.column2 = 1) and
      not exists (select 1 from table t2 where t2.ids = t.ids and t2.column3 = 1);

答案 2 :(得分:1)

我认为这应该可以解决您的问题

SELECT * 
FROM   input_table 
WHERE  id IN (SELECT Max(id) 
              FROM   input_table 
              GROUP  BY id 
              HAVING Sum(column2) < 1 
                     AND Sum(column3) < 1);
相关问题