2014-04-02 36 views
-1

我有下表;如何從組合的表中獲取最大出現值?

column 1 column 2 column 3 
1   2   X 
1   2   X 
1   2   Y 

1   3   Z 
1   3   X 

我需要編寫一個SQL查詢來獲取輸出爲;

1   2   X (because X is the maximum occurrence) 
1   3   Z or X(because number of occurrence of Z or X is same) 

我該怎麼做?

+0

什麼是您的DBMS? –

+0

我相信你可以用'GROUP BY ColumnName'和'COUNT(column)'組合來解決問題。 – Amicable

+1

http://stackoverflow.com/questions/1503959/how-to-count-occurrences-of-a -column-value-efficient-in-sql –

回答

0

我想我有一個解決方案,您使用的功能RANK(試試這個腳本),ROW_NUMBER()& DENSE_RANK(),您可以選擇您需要符合功能:

with temp as (
select 1 as col1, 2 AS col2, 'X' as col3 union all 
select 1 as col1, 2 AS col2, 'Y' as col3 union all 
select 1 as col1, 2 AS col2, 'X' as col3 union all 
select 1 as col1, 3 AS col2, 'Z' as col3 union all 
select 1 as col1, 3 AS col2, 'T' as col3 union all 
select 1 as col1, 3 AS col2, 'Y' as col3 union all 
select 1 as col1, 3 AS col2, 'Y' as col3 union all 
select 1 as col1, 4 AS col2, 'Y' as col3 union all 
select 1 as col1, 4 AS col2, 'W' as col3) 
,temp2 AS (
select 
    col1 
    ,col2 
    ,col3 
    ,COUNT(1) nb_occurence 
    ,RANK() OVER(PARTITION BY col1,col2 ORDER BY COUNT(1) DESC) Ordre_RANK 
    ,ROW_NUMBER() OVER(PARTITION BY col1,col2 ORDER BY COUNT(1) DESC) Ordre_ROW_NUMBER 
    ,DENSE_RANK() OVER(PARTITION BY col1,col2 ORDER BY COUNT(1) DESC) Ordre_DENSE_RANK 
from temp 
GROUP BY 
    col1 
    ,col2 
    ,col3) 

SELECT * 
FROM temp2 
--WHERE Ordre_RANK = 1 
--WHERE Ordre_ROW_NUMBER = 1 
--WHERE Ordre_DENSE_RANK = 1 

希望這會幫助你。

相關問題