Select a column where the row has a maximum value in a column grouped over a third column in Oracle

时间:2016-02-25 20:47:23

标签: sql oracle

In Oracle, how to select a column where the row has a maximum value in a column grouped over a third column? An example is probably easiest(I've dumbed this down for the example):

id | year | color  | groupID | typeID | personID
---+------+--------+---------+--------+---------
1  | 2010 | red    | 10      | 3      | 1
2  | 2011 | yellow | 10      | 15     | 1
3  | 2012 | blue   | 10      | 12     | 2
4  | 2009 | green  | 25      | 6      | 2
5  | 2010 | purple | 25      | 17     | 2
6  | 2011 | orange | 25      | 22     | 3

I want each output row to have the color grouped by the groupID with the max year value for that group.

What I want to see would be an output like:

1 | 2010 | blue   | 10 | 3  | 1
2 | 2011 | blue   | 10 | 15 | 1
3 | 2012 | blue   | 10 | 12 | 2
4 | 2009 | orange | 25 | 6  | 2
5 | 2010 | orange | 25 | 17 | 2
6 | 2011 | orange | 25 | 22 | 3

In other words, I want the output to MOSTLY mirror my table, but I need each rows color to match the color from the row with the maximum year within that group.

1 个答案:

答案 0 :(得分:1)

Oracle安装程序

CREATE TABLE table_name ( id,year,color,groupID,typeID,personID) AS
SELECT 1,2010,'red',10,3,1 FROM DUAL UNION ALL
SELECT 2,2011,'yellow',10,15,1 FROM DUAL UNION ALL
SELECT 3,2012,'blue',10,12,2 FROM DUAL UNION ALL
SELECT 4,2009,'green',25,6,2 FROM DUAL UNION ALL
SELECT 5,2010,'purple',25,17,2 FROM DUAL UNION ALL
SELECT 6,2011,'orange',25,22,3 FROM DUAL;

<强>查询

SELECT id,
       year,
       MAX( color ) KEEP ( DENSE_RANK LAST ORDER BY year )
                    OVER ( PARTITION BY groupID ) AS color,
       groupId,
       typeId,
       personId
FROM table_name;

<强>输出

        ID       YEAR COLOR     GROUPID     TYPEID   PERSONID
---------- ---------- ------ ---------- ---------- ----------
         1       2010 blue           10          3          1 
         2       2011 blue           10         15          1 
         3       2012 blue           10         12          2 
         4       2009 orange         25          6          2 
         5       2010 orange         25         17          2 
         6       2011 orange         25         22          3