简体   繁体   中英

How can i sum every N rows on maria db SQL?

i'm having trouble of finding a way to perform simple addition on a table of maria db, SQL.

i'm having a table called Traffic:

| start_time        | end_time          | col1 | col2 |
| 1485075600.000000 | 1485075900.000000 | 10   | 20 |
| 1485075900.000000 | 1485076200.000000 | 20   | 30 |
| 1485076200.000000 | 1485076500.000000 | 40   | 50 |
| 1485076500.000000 | 1485076800.000000 | 50   | 60 |

How can i sum every N columns (over col1, and col2) ?

i mean, to merge rows and sum the values of col1, and col2.

assuming the given table, And N = 2, the result will be:

| start_time        | end_time          | col1 | col2|
| 1485075600.000000 | 1485076200.000000 | 30   | 50  |
| 1485076200.000000 | 1485076800.000000 | 90   | 110 |

if the table size isn't a multiple of of N, take all you can.

Any one have any idea? i don't have id's to group by on.

You would do this by enumerating the rows. To be correct, you need a column to specify the ordering -- SQL tables represent unordered sets, so they need a column for the ordering.

Let me assume it is start_time . The rest is just aggregation and arithmetic:

select min(start_time) as start_time, max(end_time) as end_time,
       sum(col1) as col1, sum(col2) as col2
from (select t.*, (@rn := @rn + 1) as rn
      from traffic t cross join
           (select @rn := 0) params
      order by start_time
     ) t
group by floor( (rn - 1) / @N);

The @N value is the size of the groups.

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