2016-02-12 81 views
2

我試圖找到出現每年最下表中的USER_ID另一列值的金額: 接收者(MSGID,USER_ID,time_read)你怎麼能指望的時候一個值出現在SQL

我可以找到不同的年值:

SELECT DISTINCT EXTRACT(YEAR FROM time_read) as years FROM Recipients 

我可以找到,如果我硬編碼在今年出現,每年的大部分USER_ID:

SELECT user_ID u, cnt FROM(SELECT user_ID, COUNT(user_ID) cnt FROM Recipients WHERE EXTRACT(YEAR FROM time_read) = '2014' GROUP BY user_ID ORDER BY cnt DESC); 

但我想不出如何將這些結合起來,以得到一個表,列出每年出現最多的user_ID。

感謝

+0

這個問題怎麼可能是mysql和oracle。請選擇一個平臺 – Hogan

+1

那麼,哪個RDBMS? – Strawberry

+0

對不起,一定有意外點擊mysql – Upgrayded

回答

1

這給一試:

SELECT user_ID, count(user_ID) as cnt, EXTRACT(YEAR FROM time_read) as year 
    FROM RECIPIENTS 
    GROUP BY EXTRACT(YEAR FROM time_read), user_ID 
    ORDER BY year ASC, cnt DESC 
+0

我想你需要一個子查詢,如果你想按這些列名進行排序的話。 – Hogan

+0

關閉,它將user_ID分開並每年統計它們,但它不僅顯示每年的最大值。 – Upgrayded

+0

sqlfiddle here:http://sqlfiddle.com/#!9/bd332e/1/0 –

1

有可能是一個更簡單的方式做到這一點比這個,但我認爲這將完成的最終目標:

with counts as (
    select 
    user_id, extract (year from time_read) as year_id, 
    count (*) as cnt 
    from 
    Recipients 
    group by 
    user_id, extract (year from time_read) 
), 
max_values as (
    select 
    user_id, year_id, cnt, 
    max (cnt) over (partition by year_id) as max_cnt 
    from counts 
) 
select 
    user_id, year_id, cnt 
from max_values 
where cnt = max_cnt 

有可能你有兩個或兩個以上的用戶,在這種情況下,這將列出他們兩個。如果您想打破平局,您必須在分析功能中使用row_number()而不是count(1)

相關問題