如何计算一列值与SQL中的另一列值一起出现的次数

时间:2016-02-12 17:47:13

标签: sql oracle

我正在尝试查找下表中每年最多出现的user_ID:      收件人(msgID,user_ID,time_read)

我可以找到不同的年份值:

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的表。

由于

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)