简体   繁体   中英

Oracle DB. How to get a running total from multiple columns on one record

I have a table that stores a unique ID and 12 monthly values.

I need to provide the front-end a procedure that gives them monthly values in the first row and a running total in the second row for a specific Unique ID. (See table below for desired output).

The first part is easy since its just a simple select statement, the running total is whats tripping me up.

I looked into SUM OVER but that seems to only work if you need a running total on one column. But I have 12 different columns that have data.

What I don't want to do is just a simple Jan22, Jan22+Feb22, Jan22+Feb22+Mar22.

Anyway to go about this? Thanks.

EDIT: Table Definition

Unique ID Jan22 Feb22 Mar22
1 5000 1000 3000
2 3000 2000 8000

Desired output. The front end team calls the procedure and sends unique ID 1 as parameter.

Below is what I want to display.

Jan22 Feb22 Mar22
5000 1000 3000
5000 6000 9000

I need to provide the front-end a procedure that gives them monthly values in the first row and a running total in the second row for a specific Unique ID.

This is not a database problem; this is a display problem. You should be passing a single row with 12 columns, one for each month, and then if it needs displaying in two rows then the cumulative total should be generated at display time by the front-end and should not be calculated in the database.


If you must do it in the database (don't):

What I don't want to do is just a simple Jan22, Jan22+Feb22, Jan22+Feb22+Mar22.

Unfortunately, that's the way it should be done.

Get all the columns for the unique id and then use UNION ALL to get the row again and accumulate the values:

SELECT Jan22,
       Feb22,
       Mar22
FROM   table_name
WHERE  unique_id = 1
UNION ALL
SELECT Jan22,
       Jan22 + Feb22,
       Jan22 + Feb22 + Mar22
FROM   table_name
WHERE  unique_id = 1

Which, for the sample data:

CREATE TABLE table_name (Unique_ID, Jan22, Feb22, Mar22) AS
SELECT 1, 5000, 1000, 3000 FROM DUAL UNION ALL
SELECT 2, 3000, 2000, 8000 FROM DUAL;

Outputs:

JAN22 FEB22 MAR22
5000 1000 3000
5000 6000 9000

db<>fiddle here

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