简体   繁体   中英

sql query for each day

i have a table main:

(  
time date,  
qty int  
)  

i want to create a query so for each day i get the sum of qty on that day and all days before that so for this data

-----------------------    
time        | qty    
01/09/2009  | 3   
02/09/2009  | 8  
03/09/2009  | 2 
04/09/2009  | 5 

i get:

-----------------------    
time        | total    
01/09/2009  | 3   
02/09/2009  | 11  
03/09/2009  | 13 
04/09/2009  | 18 

thanks in advance

SELECT TIME, (SELECT SUM(QTY) FROM main m2 WHERE m2.ITME <= mt1.TIME) AS sum  
FROM main m1  
ORDER BY TIME  

This should do the trick, though it might not be the fastest solution.

SELECT
  M.Time,
  SUM(M2.Qty) RunningTotal
FROM
  Main M
  LEFT JOIN Main M2 ON M.Time >= M2.Time
GROUP BY
  M.Time;

This should give you a faster result

SELECT time
     , @tot_qty := @tot_qty+qty AS tot_qty
FROM Table1 
JOIN (SELECT @tot_qty := 0) d
order by time

SQL FIDDLE

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