开发者

sql to calculate daily totals minues the previous day's totals

I have a table that has a date, item, and quantity.

I need a sql query to return the totals per day, but the total is the quantity minus the previous day totals. The quantity accumulates as the month goes on. So the 1st could have 5 the 2nd have 12 and the 3rd has 20.

So the 1st adds 5 2nd adds 7 to make 12 3rd adds 8 to make 20.

I've done something like this in the past, but can not find it or remember. I know i'll need a correlated sub-query.

TIA

--

Edit 1

I'm using Microsoft Access. Date is a datetime field, item is a text, and quantity is number

--

Edit 2

Ok this is what i have

SELECT oos.report_date, oos.tech, oos.total_cpe, oos_2.total_cpe
   FROM oos INNER JOIN (
     SELECT oos_2.tech, Sum(oos_2.total_cpe) AS total_cpe
     FROM oos_2
     WHERE (((oos_2.report开发者_如何学C_date)<#10/10/2010#))
     GROUP BY oos_2.tech
   ) oos_2 ON oos.tech = oos_2.tech;

How do i get the oos.report_date into where i says #10/10/2010#. I thought I could just stick it in there like mysql, but no luck. I'm gonna continue researching.


Sum them by adding one to the date and making the value negative, thus taking yesterday's total from today's:

SELECT report_date, tech, Sum(total_cpe) AS total_cpe 
FROM (
    SELECT oos.report_date, oos.tech, oos.total_cpe
    FROM oos 
    UNION ALL
    SELECT oos.report_date+1, oos.tech, 0-oos.total_cpe 
    FROM oos 
)
WHERE (report_date < #10/10/2010#) 
GROUP BY report_date, tech 
ORDER BY report_date, tech 


Ok, I figured it out.

SELECT o.report_date, o.tech, o.total_cpe, 
o.total_cpe -  (
    SELECT  IIf(Sum(oos.total_cpe) is null, 0,Sum(oos.total_cpe)) AS total_cpe 
    FROM oos 
    WHERE (((oos.tech)=o.tech) AND ((oos.report_date)<o.report_date))
) AS total
FROM oos o;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜