简体   繁体   English

SQL聚合查询

[英]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. 我的第一个想法是GROUP BY Date和Rank,但这不会合并多天。 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. 事后我可以通过循环数据来执行此操作,或者我可以在存储过程中使用游标,但我很好奇是否有更简单的SQL查询方法。

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 SQLFIDDLE

Most straightforward way I can see, is what you already pointed out. 我能看到的最直接的方式就是你已经指出过的。

Use the Group By SQL: 使用Group By SQL:

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

Fiddle Demo: http://sqlfiddle.com/#!2/d65d5c/3 小提琴演示: 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. 到目前为止,我可以看到这将导致相当复杂和缓慢的SQL查询。 But maybe someone can teach me better. 但也许有人可以教我更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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