Postgres - SQL匹配第一个rownum

时间:2017-12-24 20:54:29

标签: sql postgresql

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

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...)

2 个答案:

答案 0 :(得分: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特有的。

答案 1 :(得分:0)

您可以MIN() rownum使用my_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; 字段才能使加入工作。

typo