来自 table 的具有优先条件的配置单元 sql select

hive sql select from table with prioritized condition

我想 select namenametype 来自一个叫 names 的 table,但优先 nametype

table names

name        nametype    address    id
simon           01       xx         1
simon           02       xx         2 
simon           03       xx         3 
karen           01       xx         4
william         03       xx         5 
william         01       xx         6
william         02       xx         7

我想编写一个查询,其中 select 是 name,其中 nametype = 01 或 02 或 03,按该排序顺序。 我只想要 nametype = 01 的行,其他 2 行不应该 selected.

如何在 sql 中实现此目的,我需要了解如何将名称标记为已 selected。

如果您只想要带有 01 的行,则使用 where:

select t.*
from t
where t.nametype = '01';

如果您想要具有最小值 nametype 的行(这似乎是您问题的意图),则使用 window 函数和 where。一种方法使用 min():

select t.*
from (select t.*, min(t.nametype) over (partition by name) as min_nametype
      from t
     ) t
where nametype = min_nametype;

设法使用 coalesce 弄明白了我自己

pseudocode:

if nametypes = OECD207
     select row
 elseif nametypes = OECD203
     select row
 elseif nametypes =OECD204
     select row
end if

经合组织207 经合组织203 经合组织204 ... 作为优先列表

select
navn
, coalesce(OECD207, OECD203, OECD204, ...) as nametype 
from
(
select
navn
, max(case when nametype = "OECD207" then nametype else null end) as OECD207
, max(case when nametype = "OECD203" then nametype else null end) as OECD203
, max(case when nametype = "OECD204" then nametype else null end) as OECD204
...
from ...
group by
navn
)