SQL-从Oracle SQL

时间:2018-10-06 15:56:01

标签: sql oracle oracle11g

我正在尝试从结果集中获取产品的最大值,但我仅获得一行值。我想显示结果集中每个产品的最大值。

请找到结果集:

|Col1     |col2        |col3|    col4 |sum_cnt|
+---------+------------+---------+----------+-------+
|     1003|     2018/03| PC |    Prod1| 105984| 
|     1003|     2018/03| PC |    Prod2|      3| 
|     1003|     2018/03| PC |    Prod3|    695| 
|     1003|     2018/03| PC |    Prod4|   8489| 
|     1003|     2018/02| PC |    Prod1| 101894| 
|     1003|     2018/02| PC |    Prod4|   7758| 
|     1003|     2018/02| PC |    Prod3|    780| 
|     1003|     2018/02| PC |    Prod2|      1| 
|     1003|     2018/01| PC |    Prod4|   7665| 
|     1003|     2018/01| PC |    Prod3|    708| 
|     1003|     2018/01| PC |    Prod2|      5| 
|     1003|     2018/01| PC |    Prod1| 104557| 
|     1003|     2017/12| PC |    Prod2|      2| 
|     1003|     2017/12| PC |    Prod1| 106896| 
|     1003|     2017/12| PC |    Prod3|    857| 
|     1003|     2017/12| PC |    Prod4|   8177| 
|     1003|     2017/11| PC |    Prod2|      1| 
|     1003|     2017/11| PC |    Prod1| 102664| 
|     1003|     2017/11| PC |    Prod3|    724| 
|     1003|     2017/11| PC |    Prod4|   7661| 
+---------+------------+---------+----------+-------+

我想显示每个产品的最新日期的最大sum_cnt。

我希望输出为:

|Col1     |col2        |col3|    col4 |sum_cnt|
+---------+------------+---------+----------+-------+
|     1003|     2018/03| PC |    Prod1| 106896| 
|     1003|     2018/03| PC |    Prod2|      5| 
|     1003|     2018/03| PC |    Prod3|    857| 
|     1003|     2018/03| PC |    Prod4|   8489| 

我已经尝试在下面的查询中提取数据,但是我只得到一条记录。

代码如下:

select * from tab2 a where sum_cnt = (select max(sum_cnt)  from tab2 b where a.col1= b.col1)

请帮助我实现这一目标。

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

我们可以在此处尝试使用ROW_NUMBER

SELECT Col1, col2, col3, col4, sum_cnt
FROM
(
    SELECT t.*,
        ROW_NUMBER() OVER (PARTITION BY col1, col4 ORDER BY col2 DESC, sum_cnt DESC) rn
    FROM yourTable t
) t
WHERE rn = 1;

这里的逻辑是按产品划分,然后按第一个日期递减的顺序排序,以获取最近的日期,然后按计数递减,以获取该最新日期的最高计数。

答案 1 :(得分:1)

考虑加入汇总子查询:

select t.col1, t.col2, t.col3, t.col4, agg.max_cnt
from tab2 t
inner join
    (
      select sub_t.col1, sub_t.col4, max(sub_t.col2) AS max_date, 
                                     max(sub_t.sum_cnt) as max_cnt
      from tab2 sub_t
      group by sub_t.col1, sub_t.col4
    ) agg
on t.col1 = agg.col1 and t.col4 = agg.col4 and t.col2 = agg.max_date
order by t.col4

或使用CTE:

WITH agg AS 
    (
      select sub_t.col1, sub_t.col4, max(sub_t.col2) AS max_date,  
                                     max(sub_t.sum_cnt) as max_cnt
      from tab2 sub_t
      group by sub_t.col1, sub_t.col4    
    )

select t.col1, t.col2, t.col3, t.col4, agg.max_cnt 
from tab2 t
inner join agg
on t.col1 = agg.col1 and t.col4 = agg.col4 and t.col2 = agg.max_date
order by t.col4

Rextester Demo