简体   繁体   中英

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.

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

Most straightforward way I can see, is what you already pointed out.

Use the Group By SQL:

SELECT  date, rank, SUM(vote) FROM YourTable
GROUP BY date, rank

Fiddle Demo: http://sqlfiddle.com/#!2/d65d5c/3

Iterate through this record set in your program and do what is needed to get your data. (If you tag your question with a programming language, I can show you how).

So basically no, I can't see any better way to do this. As far I can see this would end up in a fairly complicated and slow SQL query. But maybe someone can teach me better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM