Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

mysql - Sum the values of a column based on a group of values from another column

I have a table where each transaction is associated to a given price. Something like this:

transaction  price  
     1        10  
     2        20  
     3        30  
     5        50  
     6        10  
    10        10  
    23        10  
    24        10  
    25        10  
    26        10  
    27        10  

I'm trying to find a way to sum the price based on a specific transaction or for a group of transactions. The result of the query would be something like this:

transaction  price
   1-3        60
   5-6        60
    10        10
 23-27        50

This way I can tell that for the transactions 1 to 3 the result was 60, and so on. Can you point me in the right direction to make this using MySQL?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since mysql doesn't have support for windowing functions, we have to create our own group ranking for your table, and then another query to operate on the results.

select if(count(transaction) = 1, transaction, concat(min(transaction), '-', max(transaction))) transactions, sum(price) price 
  from (
    select if(`transaction` = @prev + 1, 
         if(@prev := `transaction`, @rank, @rank),
           if(@prev := `transaction`, @rank := @rank + 1, @rank := @rank + 1)
       ) gr,
       `transaction`,
       price
    from table1, (select @rank := 1, @prev := 0) q
    order by `transaction` asc
  ) q     
  group by gr

demo here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...