简体   繁体   English

sql计算每日总计减去前一天的总计

[英]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. 我需要一个sql查询来返回每天的总数,但总数是数量减去前一天的总数。 The quantity accumulates as the month goes on. 数量随着月份的增加而累积。 So the 1st could have 5 the 2nd have 12 and the 3rd has 20. 因此,第一个可能有5个,第二个可能有12个,第三个可能有20个。

So the 1st adds 5 2nd adds 7 to make 12 3rd adds 8 to make 20. 因此,第1加5第2加7做12第3加8做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 TIA

-- -

Edit 1 编辑1

I'm using Microsoft Access. 我正在使用Microsoft Access。 Date is a datetime field, item is a text, and quantity is number 日期是日期时间字段,项目是文本,数量是数字

-- -

Edit 2 编辑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_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#. 我如何将oos.report_date放入我说#10/10/2010#的位置。 I thought I could just stick it in there like mysql, but no luck. 我以为我可以像mysql一样贴在里面,但是没有运气。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM