简体   繁体   中英

Calculating the sequence of data from a table

I have a table being generated from some sql. I need to further attain from this the following rule but am stuck and would greatly appreciate some assistance.

For each 3 consecutive Cycles, add the number of Days.

The current table is derived on a more complex calculated version of SQL to generate the table, the below is it drummed down to the basic:

SELECT Cycle, Days
FROM Leave

Current Table:

 - Cycle: 1,2,3,4,5,6,7,8
 - Days: 7,8,7,6,9,5,4,9

Desired Result

在此处输入图片说明

Although you did not mentioned your DBMS name, following 2 solutions as for MSSQL and MySQL. You can also apply the same logic if you have other DBMS.

MSSQL:

SELECT 
CAST(A.cycle AS VARCHAR) 
    +','+ CAST(B.cycle AS VARCHAR) 
    +','+ CAST(C.cycle AS VARCHAR) Cycles, 
A.days+B.days+C.days Days
FROM your_table A
CROSS APPLY your_table B
CROSS APPLY your_table C
WHERE C.cycle = B.cycle+1 AND B.cycle = A.cycle+1
ORDER BY A.cycle

MySQL:

SELECT 
CONCAT(CAST(A.cycle AS CHAR) 
    ,',', CAST(B.cycle AS CHAR) 
    ,',', CAST(C.cycle AS CHAR)) Cycles, 
A.days+B.days+C.days Days
FROM your_table A
CROSS JOIN your_table B
CROSS JOIN your_table C
WHERE C.cycle = B.cycle+1 AND B.cycle = A.cycle+1
ORDER BY A.cycle;

You can use cumulative sum:

select t.*,
       sum(days) over (order by cycle rows between 2 preceding and current row)
from t;

Note: For the first two rows, you will get values that are not the sum of three days. One way to handle this is to use lag() instead:

select t.*,
       (days +
        lag(days, 1) over (order by cycle) +
        lag(days, 2) over (order by cycle)
       )
from t;

This will return NULL for the first two rows.

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