根据 Teradata 中的特定条件检索 table 数据

Retrieve table data based on specific condition in Teradata

我有一个 table 数据如下:

emp_id | emp_sal | emp_grp

1          5       HMCCR
1         10       HMCPR
1         20       HMCPR
1         30       HMCPR
1         40       HMCRR
2         40       HMCRR
2         50       HMCCR

我需要在 Teradata 中编写 sql,我需要为每组 emp_id.If 找到 min(emp_sal) 一个或多个 emp_id 行具有 emp_grp='HMCPR' 然后只保留那些行并取最小 emp_sal。当 none 行有 emp_grp='HMCPR' 时不要做任何事情,并从该组中取最小值 emp_sal。

抱歉,如果您感到困惑。基于以上条件,我的输出应该是这样的:

emp_id | emp_sal | emp_grp

1         10       HMCPR
2         40       HMCRR

我尝试了下面的查询,但它为每个组提供了 min(emp_sal),因为我使用 emp_id、emp_grp

sel
emp_id,
case when emp_grp='HMCPR' then min(emp_sal)
else min(emp_sal) end emp_sal,  emp_grp

from db_wrk.emp_sin 
group by emp_id, emp_grp

任何人都可以帮助我在 teradata 中获得预期的结果。

您可以使用 row_number 和一些逻辑来让 emp_grp HMCPR 在存在时首先被订购。

select emp_id,emp_sal,emp_grp 
from (
select e.*, 
row_number() over(partition by emp_id 
                  order by case when emp_grp = 'HMCPR' then 0 else 1 end,emp_sal) as rn
from db_wrk.emp_sin e
) t
where rn = 1