2013-02-21 49 views
2

我需要能夠按兩列進行分組,並且只能將這兩列的另一列的ID爲最大值的行取回。之後我的細節是,在第四列說被叫應答按兩列和另一列的最大值分組

COLUMN1 | COLUMN2 | NUMBERCOL | Answer 
--------------- ---------------------------- 
123 | 456 |  1  | a 
123 | 456 |  2  | x 
123 | 456 |  3  | s 
654 | 564 |  1  | a 
654 | 564 |  2  | s 
654 | 564 |  3  | p 
654 | 564 |  4  | b 

所以我需要答案期從從第二組第一分組結果和答案b。結果

回答

3

您可以使用一個JOIN子查詢得到的結果:

select t1.column1, 
    t1.column2, 
    t1.numbercol, 
    t1.answer 
from yourtable t1 
inner join 
(
    select column1, column2, 
    max(numbercol) MaxNum 
    from yourtable 
    group by column1, column2 
) t2 
    on t1.column1 = t2.column1 
    and t1.column2 = t2.column2 
    and t1.numbercol = t2.MaxNum 

SQL Fiddle with Demo

+0

這個工作完美,歡呼聲,再加上沒有seqnum列產生。 – Standage 2013-02-21 16:44:40

+0

@Standage歡迎您,很高興它工作。 – Taryn 2013-02-21 16:45:02

2

您可以使用分析功能,此:

select t.* 
from (select t.*, 
      row_number() over (partition by column1, column2 order by numbercol desc) as seqnum 
     from t 
    ) t 
where seqnum = 1 

這工作不是通過彙總數據,而是通過指定一個序列號,該行。對於(column1,column2)的每個新值,序號重新開始,並且排序由numbercol確定。最高的numbercol值爲1,次高的爲2,依此類推。這是Oracle中分析函數的一個例子(在其他數據庫中稱爲「窗口」函數)。

最後的where子句選擇你想要的行 - numbercol最高的行。

+0

+1尼斯的答案 - 這裏有一個演示:http://sqlfiddle.com/#!4/6cedf/1 – sgeddes 2013-02-21 16:36:00

+0

不錯,這就是爲什麼你需要最後一部分,其中seqnum = 1? – Standage 2013-02-21 16:38:49

相關問題