根据分组依据中的最小值选择值

  • 本文关键字:最小值 选择 sql
  • 更新时间 :
  • 英文 :


这是我表中的数据

XDATE       AC      BN      XPASS           UCODE   LVL
31-AUG-13   C-3     301     25-SEP-13       5465189  4
31-AUG-13   C-3     304     25-SEP-13       5465189  4
31-AUG-13   C-1     104     27-SEP-13       1000020  3
31-AUG-13   C-1     104     27-SEP-13       6461005  4

这是我正在执行的查询

select 
    AC,
    BN,
    (case when count(*)>1 then 'Forwarded' else 'Prepared' end) status,
    min(LVL) 
from adsalarypreparationdtl 
group by AC,BN 

这给了我以下结果:

AC       BN         STATUS         LVL
C-1      104        Forwarded       3
C-3      301        Prepared        4
C-3      304        Prepared        4

我找到了一切,但我也想要根据 LVL 的最小值进行 UCODE

例如,像这样:

AC       BN      STATUS     UCODE       LVL
C-1      104     Forwarded  1000020     3
C-3      301     Prepared   5465189     4
C-3      304     Prepared   5465189     4

请帮忙。

你没有说明你的DBMS,所以这是ANSI SQL:

select AC,
       BN,
       ucode, 
       lvl
from (
    select ac, 
           bn,
           ucode,
           lvl, 
           row_number() over (partition by AC,BN order by lvl) as rn
    from adsalarypreparationdtl 
) t 
where rn = 1;

怎么样

select q1.*,q2.ucode
from (YourQuery) q1
left join adsalarypreparationdtl q2
on q1.ac=q2.ac and q1.bn=q2.bn and q1.minlvl=q2.lvl

在查询中,应将 min(lvl) 列别名为 minlvl。

可能它效率不高,但会起作用。

编辑:如果有 2 行或更多行具有相同的 lvl,您是否需要任何特殊处理?

最新更新