Oracle Sql:特定字段中的不同值

时间:2015-05-06 19:47:35

标签: sql oracle distinct

我有下表:

  **Country     Name        Number**
   us           John         45
   us           Jeff         35
   fr           Jean         31
   it           Luigi        25
   fr           Maxime       23
   ca           Justin       23

此表按编号排序。我希望得到一个查询,每个国家/地区都会给我一个最高编号的名称:

  **Country     Name        Number**
   us           John         45
   fr           Jean         31
   it           Luigi         25
   ca           Justin        23

我尝试使用不同但我只能在国家/地区制作,如果我想打印所有内容...

有个主意吗?'

编辑: 该表由子查询

获取

4 个答案:

答案 0 :(得分:1)

尝试以下查询:

SELECT Country, MAX(numbeer) FROM Table_Name GROUP BY Country

PFB更新了查询以包含名称:

SELECT t1.* FROM table1 t1 INNER JOIN 
(SELECT country, max(numbeer) as numbeer FROM table1 GROUP BY country) t2
ON t1.country=t2.country AND t1.numbeer=t2.numbeer;

答案 1 :(得分:1)

我没有Oracle数据库方便,但我在我的SQL Server数据库中工作,我很确定它可以在Oracle中工作(这意味着我认为我使用的是ANSI sql,它应该适用于大多数数据库) :

SELECT m.Country,m.Name,m.number
FROM mytable m
INNER JOIN (
    select country, MAX(number) as number 
    FROM mytable GROUP BY Country
) AS tmp ON m.Country = tmp.Country and m.Number = tmp.number
ORDER BY m.Number DESC

这样做的另一个好处是,如果某个国家/地区的两个人拥有相同的号码,它应该会为您提供记录。

你没有给我们一个表名,所以我只称它为mytable。

答案 2 :(得分:1)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE Countries AS
          SELECT 'us' AS Country, 'John' AS Name, 45 AS "Number" FROM DUAL
UNION ALL SELECT 'us' AS Country, 'Jeff' AS Name, 35 AS "Number" FROM DUAL
UNION ALL SELECT 'fr' AS Country, 'Jean' AS Name, 31 AS "Number" FROM DUAL
UNION ALL SELECT 'it' AS Country, 'Luigi' AS Name, 25 AS "Number" FROM DUAL
UNION ALL SELECT 'fr' AS Country, 'Maxime' AS Name, 23 AS "Number" FROM DUAL
UNION ALL SELECT 'ca' AS Country, 'Justin' AS Name, 23 AS "Number" FROM DUAL;

查询1

SELECT Country,
       MAX( Name ) KEEP ( DENSE_RANK FIRST ORDER BY "Number" DESC ) AS "Name",
       MAX( "Number" ) AS "Number"
FROM   Countries
GROUP BY Country

<强> Results

| COUNTRY |   Name | Number |
|---------|--------|--------|
|      ca | Justin |     23 |
|      fr |   Jean |     31 |
|      it |  Luigi |     25 |
|      us |   John |     45 |

答案 3 :(得分:0)

使用row_number()

select t.Country, t.Name, t.Number
from (select t.*,
             row_number() over (partition by country order by number desc) as seqnum
      from table t
     ) t
where seqnum = 1;