检索oracle DB的每组记录的最大数量

时间:2015-12-14 14:41:18

标签: sql oracle toad

我无法编写SQL代码来检索order_number列中的最大数量。 注意visit_number是group包含多个记录,我想要order_number列的最大值。

visit_number , Order_number , NAME
111          ,     1        , 001
111          ,     2        , 001
111          ,     3        , 001
222          ,     1        , 252
222          ,     2        , 252 
003          ,     1        , 121
003          ,     2        , 121

我希望结果如下所示:

111          ,     3        , 001
222          ,     2        , 252 
003          ,     2        , 121

这是我的查询

SELECT VISIT_NUMBER , MAX(ORDER_NUMBER) , NAME
from table
group by ( visit_number , name ) 

3 个答案:

答案 0 :(得分:0)

使用GROUP BYMAX功能。

SELECT visit_number, MAX(Order_number), NAME
FROM yourtable
GROUP BY visit_number, NAME

答案 1 :(得分:0)

使用子查询加入表,该子查询返回每个visit_number及其最大order_number:

SELECT distinct t1.*
FROM tablename t1
  JOIN (select visit_number, MAX(Order_number) as max_Order_number
        from tablename group by visit_number) as t2
  ON t1.visit_number = t2.visit_number and t1.Order_number = t2.max_Order_number

(如果最大订单号有多个不同的名称,将返回所有行。)

答案 2 :(得分:0)

select VISIT_NUMBER, ORDER_NUMBER, NAME
from (
select VISIT_NUMBER, ORDER_NUMBER, NAME, row_number() over(partition by VISIT_NUMBER order by ORDER_NUMBER desc) as ORDER_DESC
from TABLE
)
where ORDER_DESC = 1

这将返回每个VISIT_NUMBER的最大值,即使NAME更改