Oracle查询选择

时间:2013-10-10 04:21:53

标签: sql database oracle

我有一个表格说Variables,其中存在一个名为“name”的列。该字段的值类似于 -

    abc_R01
    abc_R02
    abc_R03
    pqrs_R01
    pqrs_R02
    xyz_R01
    xyz_R02
    xyz_R03
    xyz_R04

现在我的选择标准就像我必须选择每个的最新变量名,即我可以触发单个/复杂查询来获得结果,如 -

    abc_R03
    pqrs_R02
    xyz_R04

或者我需要通过我的代码处理它,这里_Rxx表示我的变量的修订版。 请帮帮我。

3 个答案:

答案 0 :(得分:1)

select name
from
(
select 
  substr("name",0,length("name")-1) as n1,max("name") as name
from Table1
   group by substr("name",0,length("name")-1)
)t

<强> SQL Fiddle

答案 1 :(得分:1)

请尝试:

select 
  Col
from
(
  select
    Col,
    row_number() over (partition BY substr(Col, 0, instr(Col, '_')) order by regexp_substr(col, '\d+$') DESC) rn
  from YourTable
)x where rn=1;

在10 G

中检查以下查询
select 
  Col
from
(
  select
    Col,
    row_number() over (partition BY substr(Col, 0, instr(Col, '_')) order by substr(col, instr(col, 'R')+1) DESC) rn
  from YourTable
)x where rn=1;

SQL Fiddle Demo

答案 2 :(得分:1)

这对你也有帮助,

WITH t(NAME) AS
(
SELECT 'abc_R01' FROM dual
UNION
SELECT 'abc_R02' FROM dual
UNION
SELECT 'abc_R03' FROM dual
UNION
SELECT 'pqrs_R01' FROM dual
UNION
SELECT 'pqrs_R02' FROM dual
UNION
SELECT 'xyz_R01' FROM dual
UNION
SELECT 'xyz_R02' FROM dual
UNION
SELECT 'xyz_R03' FROM dual
UNION
SELECT 'xyz_R04' FROM dual
)
SELECT NAME
FROM (
     SELECT substr(NAME, 0, instr(NAME, 'R')),
            MAX(NAME) NAME
     FROM  t
     GROUP BY substr(NAME, 0, instr(NAME, 'R'))
     );