简体   繁体   中英

How to sum in sql DB2

so I have a table calls orders for example in this table I have these values

   name    volume    price
1- Cisco    300       27
2- Cisco    150       26
3- Cisco     50       26

I am trying to use this query:

select o.name, sum(o2.volume), o.price
from orders o, orders o2
where o.price <= o2.price
group by o.name, o.price

but this query returns this:

   name    volume    price
1- Cisco    300       27
2- Cisco    200       26

But I want this results:

   name    volume    price
1- Cisco    300       27
2- Cisco    500       26

In second row should be the sum of sales of: sales with bigger price (1) + sum of all sales with lower price (2+3)

There is not a built in function to get the previous row, however you can sort your data and use window function to get the row_number() , and then use a case statement.

ROW_NUMBER() OVER tells DB2 how you want the rows numbered. If you are selecting the company name, telling it to ROW_NUMBER() OVER (ORDER BY PRICE DESC) would have the row with the highest PRICE as #1, the second highest as #2, etc.

I suggest you to check the documentation and come back with an example of what you have done so far so we can start from there.

I got it, so I did this:

select o.name, (select sum(o2.volume) from orders o2 where o2.price <= o.price and o2.name = o.name), ,o.price from orders o group by o.name, o.price

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