Postgres - SQL匹配第一个rownum

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

我有以下SQL为每条记录生成一个行num

MY_VIEW AS
    ( SELECT
            my_id, 
            (case when col1 = 'A' then
                        1
                  when col1 = 'C' then
                        2
                  else
                        3
                  end) as rownum
from table_1

所以我的数据看起来像这样:

my_id        rownum
0001-A         1
0001-A         2
0001-B         2

后来,我想为每个唯一的“my_id”使用最小的rownum来做另一个table_2的内连接。我该怎么办?这就是我到目前为止所拥有的。

select * from table_2 
inner join tabl_1
     on table_2.my_id = table1.my_id
     and row_num = (...the smallest from M_VIVE...)
sql postgresql
2个回答
0
投票

在Postgres,我会推荐distinct on

selecd distinct on (my_id) my_id
       (case when col1 = 'A' then 1
             when col1 = 'C' then 2
             else 3
        end) as rownum
from table_1
order by my_id, rownum;

但是,您可以使用group by轻松完成此操作:

select my_id,
       min(case when col1 = 'A' then 1
                when col1 = 'C' then 2
                else 3
           end) as rownum
from table_1
group by my_id;

distinct on方法允许您包含其他列。它可能会快一点。在缺点方面,它是Postgres特有的。


0
投票

你可以使用MIN()函数为rownummy_id中的每个table_1并在连接中使用它。

你需要确保table_2也有my_id字段来使加入工作。

select * 
from 
table_2 
inner join 
(select my_id, MIN(rownum) as minimum_rownum from tabl_1 group by my_id) t1
on table_2.my_id = t1.my_id;
© www.soinside.com 2019 - 2024. All rights reserved.