为一列选择distinct

时间:2017-11-14 13:08:33

标签: sql db2

我有一个复合主键,其中单个部分可能是随机的。它们没有任何特定的顺序,一个可以是唯一的,也可以是完全相同的。

我不在乎我得到哪一行。这就像“只需从每个组中挑选一个”。

我的表:

KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
11       22       39                 d2
12       21       39                 d2
12       22       39                 d3
13       21       38                 d3
13       22       38                 d5

现在我想要的是获取colD中的每个条目一行,我不关心哪一个。

KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
12       21       39                 d2
12       22       39                 d3
13       22       38                 d5

3 个答案:

答案 0 :(得分:1)

以下几乎适用于任何版本的DB2:

select t.*
from (select t.*,
             row_number() over (partition by KeyPart1, KeyPart2
                                order by KeyPart1
                               ) as seqnum
      from t
     ) t
where seqnum = 1;

如果您只关心列d和前两个关键部分,那么您可以使用group by

select KeyPart1, KeyPart2, min(colD)
from t
group by KeyPart1, KeyPart2;

答案 1 :(得分:1)

对于colD唯一的行,您必须决定丢弃哪些其他列值。在over clause内,我使用了partition by colD,该列提供了该列所需的唯一性,但order by是任意的,您可能需要根据自己的需要进行更改。

select
       d.*
from (
      select 
             t.*
           , row_number() over (partition by t.colD
                                order by t.KeyPart1,t.KeyPart2,t.KeyPart) as rn
      from yourtable t
     ) d
where d.rn = 1;

答案 2 :(得分:0)

如有必要,请更改'order by'

with D as (
select distinct ColdD from yourtable
)
select Y.* from D
inner join lateral
(
   select * from yourtable X
   where X.ColdD =D.ColdD 
   order by X.KeyPart1, X.KeyPart2, X.KeyPart3
   fetch first rows only

) Y on 1=1
相关问题