删除重复项时,选择查询相关数据

时间:2017-12-20 14:59:38

标签: sql sql-server sql-server-2008 tsql

我有一张这样的表:

ID  Col_A   Col_B   Col_C   Col_D   Col_E   Col_F   Col_G   Col_H
1   yyy     null    NULL    NULL    NULL    NULL    NULL    1
1   yyy     null    NULL    NULL    NULL    NULL    NULL    null
1   yyy     null    NULL    NULL    NULL    NULL    NULL    0
1   yyy     null    NULL    NULL    NULL    NULL    NULL    null
1   yyy     null    NULL    NULL    NULL    NULL    NULL    0
26  null    17,5    NULL    NULL    NULL    NULL    NULL    null
26  null    17,5    NULL    NULL    NULL    NULL    NULL    1
26  null    17,5    NULL    NULL    NULL    NULL    NULL    0
26  null    17,5    NULL    NULL    NULL    NULL    NULL    0
26  null    17,5    NULL    NULL    NULL    NULL    NULL    1

我想删除重复的ID,但保留相关数据。所以期望的结果是:

ID  Col_A   Col_B   Col_C   Col_D   Col_E   Col_F   Col_G   Col_H
1   yyy     null    NULL    NULL    NULL    NULL    NULL    1
26  null    17,5    NULL    NULL    NULL    NULL    NULL    1

我试过的代码是:

  SELECT ID, 
  MAX (ISNULL (Col_A, 0)) AS Col_A,
  MAX (ISNULL (Col_B, 0)) AS Col_B,
  MAX (ISNULL (Col_C, 0)) AS Col_C,
  MAX (ISNULL (Col_D, 0)) AS Col_D,
  MAX (ISNULL (Col_E, 0)) AS Col_E,
  MAX (ISNULL (Col_F, 0)) AS Col_F,
  MAX (ISNULL (Col_G, 0)) AS Col_G,
  MAX (ISNULL (Col_H, 0)) AS Col_H
  FROM TableA
  GROUP BY ID
  ORDER BY 1

使用MSSQL 2008

1 个答案:

答案 0 :(得分:2)

我会这样做:

select max(col_a) as col_a,
       max(col_b) as col_b,
       . . .
from tablea
group by id
order by id;

isnull()是不必要的。