如何根据列值的优先级进行查询

bsxbgnwa  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(336)

我有一张table

| group | col1   | col2 |
| 1     | test1  | val1 |
| 1     | test2  | val2 |
| 3     | test3  | val3 |
| 3     | test4  | val4 |

我需要按优先级选择行。例如,如果行的col1值为test1,那么显示它。如果不是,则显示test2。不记得小组的事了。如果一组中有一个值。我期待这个结果:

| group | col1   | col2 |
| 1     | test1  | val1 |
| 3     | test3  | val3 |
vaj7vani

vaj7vani1#

请使用下面的查询,

select * from 
(select group, col1, col2, row_number() over (partition by group order by col1) as rnk
from table) where rnk = 1;
r55awzrz

r55awzrz2#

在标准sql中,您似乎希望:

select t.*
from t
order by (case when col1 = 'test1' then 1
               when col2 = 'test2' then 2
               else 3
          end)
fetch first 1 row only;

编辑:
对于修改后的问题,您可以使用 distinct on :

select distinct on (group) t.*
from t
order by group,
         (col1 = 'test1') desc,
         (col1 = 'test2') desc;
jc3wubiy

jc3wubiy3#

这是有效的查询!

select * from 
(select group, 
        col1, 
        col2, 
        row_number() over (partition by group order by (case when col1 = 'test1' then 2
               when col1 = 'test2' then 1
               else 3
          end)) as rnk
from test) AS tab1 where rnk = 1;

相关问题