2013-11-14 80 views
1

這個問題很難想出一個可以理解的標題。 我會嘗試用一個例子來解釋。如何在兩列中選擇最大值的記錄?

首先我有一個簡單的表INFO Oracle數據庫中:

year  type  message 
----  ----  ------- 
2001  1   cakes are yammy 
2003  2   apples are dangerous 
2012  2   bananas are suspicious 
2005  3   cats are tricky 

,我需要選擇特定類型的最新消息(例如type = 1type = 2):所以我用

2001  1   cakes are yammy 
2012  2   bananas are suspicious 

查詢(順便說一句,在這種情況下是否正確?):

select * from INFO i 
where year = (select max(year) from INFO i_last where i.type = i_last.type) 
and i.type in (1, 2) 

但現在我需要在我的INFO表中添加一個新的「季度」列。並按年份和季度選擇最新的記錄。

year  quarter  type  message 
----  -------  ----  ------- 
2001  2   1   cakes are yammy 
2012  3   2   onions are cruel 
2012  1   2   bananas are suspicious 
2005  1   3   cats are tricky 

1型或2的最新記錄將是:

2001  2   1   cakes are yammy 
2012  3   2   onions are cruel 

我無法想象能做到這一點查詢,並希望你能幫幫我吧。

回答

4

分析功能,是你的朋友:

SELECT MAX(year ) KEEP (DENSE_RANK LAST ORDER BY year ASC, quarter ASC, message ASC) AS year, 
     MAX(quarter) KEEP (DENSE_RANK LAST ORDER BY year ASC, quarter ASC, message ASC) AS quarter, 
     MAX(message) KEEP (DENSE_RANK LAST ORDER BY year ASC, quarter ASC, message ASC) AS message, 
     type 
FROM  info 
GROUP BY type; 

SQLFIDDLE

+0

在MS Access中是否有等價物?你的回答爲人們打開了一個全新的世界。 – BKSpurgeon

1

給這一個鏡頭:

SELECT i.year, i.quarter, i.type, i.message 
FROM INFO i 
JOIN INFO iy 
    ON i.type = iy.type 
JOIN INFO iq 
    ON iq.type = iy.type  
WHERE i.type IN (1,2) 
GROUP BY i.year, i.quarter, i.type, i.message 
HAVING i.year = MAX(iy.year) AND i.quarter = MAX(iq.quarter) 
+0

該位阻止我獲取唯一的結果:「AND i.quarter = MAX (iq.quarter)「 - 有什麼想法? – BKSpurgeon