SQL sum then find max

时间:2017-05-16 09:37:11

标签: sql derby

Here's what I'm trying to achieve. Basically I have a relation in which I have a count for each ID and month. I'd like to sum the counts for each id by month (middle table in the picture) and then from that find the maximum value from all those sums by month, and show the month, id, and the maximum value in that order. Here's what I've got so far:

SELECT month, MAX(summed_counts) AS maximum_result
FROM
 (SELECT month, id, SUM(counts) AS summed_counts
  FROM info WHERE year=2017 GROUP BY month, id)
AS final_result GROUP BY month ORDER BY month ASC;

However as soon as I add id it no longer works:

SELECT month, id, MAX(summed_counts) AS maximum_result
FROM
 (SELECT month, id, SUM(counts) AS summed_counts
  FROM info WHERE year=2017 GROUP BY month, id)
AS final_result GROUP BY month, id ORDER BY month ASC;

Any suggestions?

1 个答案:

答案 0 :(得分:0)

试试这个(MS SQL):

select distinct month, 

    (select top 1 SUM(counts)
        FROM info info_detail
        WHERE year=2017 and info_detail.month=info.month
        GROUP BY id
        order by SUM(counts) desc
    ) as max_value,

    (select top 1 id 
        FROM info info_detail
        WHERE year=2017 and info_detail.month=info.month
        GROUP BY id
        order by SUM(counts) desc
    ) as max_value_id

    from info 
    where year=2017
    ORDER BY month
相关问题