Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Aggregation Query

I have a dataset that I need to do some aggregation on to display.

Date,     Rank, Vote

07/20/2013, 8, -1 
07/21/2013, 8, -1 
07/23/2013, 7, -1 
07/24/2013, 6, 1
07/25/2013, 7, 1 
07/26/2013, 7, -1 
07/27/2013, 8, 1 
07/28/2013, 8, 1
07/29/2013, 8, -1

I'd like to group by consecutive ranks, summing the vote, and choosing the first of the grouped dates. The above data set would return:

07/20/2013,8,-2
07/23/2013,7,-1
07/24/2013,6,1
07/25/2013,7,0
07/27/2013,8,1

My first thought was GROUP BY Date and Rank but that wouldn't consolidate multiple days. I can do this after the fact by looping thru the data or I can use a cursor within a stored procedure but I'm curious if there is a simpler way with a SQL query.

like image 236
Soma Holiday Avatar asked Dec 05 '25 05:12

Soma Holiday


1 Answers

This does it:

SELECT firstDate, Rank, SUM(vote) Votes
FROM (
    SELECT @first_date := CASE WHEN Rank = @prev_rank
                               THEN @first_date
                               ELSE Date
                          END firstDate,
           @prev_rank := Rank curRank,
           data.*
    FROM (SELECT @first_date := NULL, @prev_rank := NULL) init
    JOIN (SELECT Date, Rank, Vote
          FROM MyTable
          Order by Date) data
    ) grouped
GROUP BY firstDate, Rank

SQLFIDDLE

like image 99
Barmar Avatar answered Dec 07 '25 22:12

Barmar