Home > database >  Get the amount in two days
Get the amount in two days

Time:10-23

I'm trying to write a query that will return the amount of sales given the previous day. I am doing a test task for an internship device but have not done this before.

Source table:

saledate salesum
2022-01-01 100
2022-01-02 150
2022-01-03 200
2022-01-05 100

Estimated result:

saledate salesum
2022-01-01 100
2022-01-02 250
2022-01-03 350
2022-01-05 300

My query:

SELECT t1.saledate, t1.salesum=t1.salesum t2.salesum 
FROM sales t1
INNER JOIN (
  SELECT saledate, salesum FROM sales 
) t2 
ON t1.saledate=t2.saledate;

My result:

saledate salesum
2022-01-01 f
2022-01-02 f
2022-01-03 f
2022-01-05 f

CodePudding user response:

select  saledate
       ,salesum   coalesce(lag(salesum) over(order by saledate),0) as salesum
from    t
saledate salesum
2022-01-01 100
2022-01-02 250
2022-01-03 350
2022-01-05 300

Fiddle

  • Related