在编写SQL查询时需要帮助

时间:2012-11-29 10:39:37

标签: oracle oracle10g top-n

我在编写以下功能的SQL查询时遇到了一个问题: 请考虑下表:

---------------------------------
 AccountNumber     JobNumber
---------------------------------
    1234            1111113
    1234            1111112
    1234            1111111
    1212            1111131
    1212            1111132

我想获取传递给查询的帐号的最新作业号。例如:如果我将1234作为帐号传递,我需要获得1111113,如果我传递1212,我应该得到1111131.如何编写PL / SQL查询来实现此目的?我们会传递多个帐号,例如AccountNumber IN ('1234','1212')。因此,对于每个帐号,我需要获取最新的工作号码。

目前我已经尝试过不使用IN这样:

SELECT * 
  FROM (SELECT JobNumber 
          FROM TABLE1 
          WHERE AccountNumber = ?) 
 WHERE ROWNUM = 1

并且在Java JDBC中我循环使用帐号ArrayList并对Oracle db执行JDBC。但是如你所知,这不是一个可行的解决方案,如果有4000个帐户性能点击。

你能帮忙写一下这个SQL查询吗?

编辑:这里最新意味着最高职位数,例如:1111113和1111112. 1111113是最新数据

4 个答案:

答案 0 :(得分:1)

有几种方法:

SQL> create table t1(AccountNumber, JobNumber) as
  2  (
  3  select 1234,  1111113 from dual union all
  4  select 1234,  1111112 from dual union all
  5  select 1234,  1111111 from dual union all
  6  select 1212,  1111131 from dual union all
  7  select 1212,  1111132 from dual
  8  )
  9  ;

Table created




SQL> select t.AccountNumber
  2       , max(t.JobNumber) as JobNumber
  3    from t1 t
  4   where AccountNumber in (1212, 1234)  -- for example
  5   group by AccountNumber
  6  ;

ACCOUNTNUMBER  JOBNUMBER
------------- ----------
         1234    1111113
         1212    1111132

OR

SQL> select AccountNumber
  2       , JobNumber
  3    from ( select t.AccountNumber
  4                , t.JobNumber
  5                , row_number() over(partition by t.AccountNumber order by t.JobNumber desc) rn
  6             from t1 t
  7            where AccountNumber in (1212, 1234) -- for example
  8         ) t
  9  where t.rn = 1
  10  ;

ACCOUNTNUMBER  JOBNUMBER
------------- ----------
         1212    1111132
         1234    1111113

OR

SQL> select AccountNumber
  2       , JobNumber
  3    from ( select t.AccountNumber
  4                , t.JobNumber
  5                , max(JobNumber) over(partition by t.AccountNumber) mjn
  6             from t1 t
  7            where AccountNumber in (1212, 1234)   -- for example
  8         ) t
  9  where t.JobNumber = t.mjn
  10  ;

ACCOUNTNUMBER  JOBNUMBER
------------- ----------
         1212    1111132
         1234    1111113

SQL> 

答案 1 :(得分:1)

简单的max()不会起作用吗?

SELECT max(JobNumber)
FROM TABLE1 
WHERE AccountNumber = ?

对于一个查询中的多个帐户:

SELECT AccountNumber, max(JobNumber)
FROM TABLE1 
WHERE AccountNumber IN (?, ?, ?)
GROUP BY AccountNumber;

答案 2 :(得分:0)

我首先从标准SQL开始。我希望以下内容能够实现。

SELECT JobNumber 
FROM TABLE1 
WHERE id = (SELECT MIN(id)
           FROM TABLE1
           WHERE AccountNumber = ?)

答案 3 :(得分:0)

select a, j1
from(                
 select 
      id, 
      a, 
      j, 
      first_value(j) over(partition by a order by id) j1
 from (                
    select AccountNumber a, JobNumber j, row_number() over(order by 0) id
    from table1) t
    ) t1
group by a, j1