在访问中运行总查询

时间:2016-08-13 19:39:11

标签: sql ms-access

我一直试图解决这个问题一段时间没有成功。我不是一个优秀的Sql程序员,所以我来找专家......我正在使用Access 2010.我有一个数据库(交易),包含以下字段:

    Entry time   -- Date/Time
    Profit       -- Number

我想根据日期提取一部分记录(例如2016年7月1日至2016年8月1日),并且在此摘录中的总计利润为。

以下查询让我关闭,但输出显示我在交易中的所有记录,并在我想要的时间段内运行总计。对于开始时间之前的记录,运行总计为空白。对于结束时间之后显示的记录,运行总计与结束时间的计算结果相同。输出看起来像是7/26 - 7/28的时间段:

    Entry time            Profit    Total
    7/14/2016 9:39:51 AM    2   
    7/14/2016 9:48:26 AM    0.25    
    7/26/2016 10:06:04 AM   -0.75   -0.75
    7/26/2016 10:29:29 AM   -1.25   -2
    7/26/2016 11:03:51 AM   2        0
    7/27/2016 9:29:52 AM    0.5      0.5
    7/27/2016 9:52:51 AM    -1.25   -0.75
    7/27/2016 10:01:56 AM   -0.75   -1.5
    7/28/2016 9:44:25 AM    -1.25   -2.75
    7/28/2016 10:44:15 AM   0.25    -2.5
    8/1/2016 9:46:43 AM      0.5    -2.5
    8/1/2016 10:02:00 AM    2       -2.5

创建此代码的代码是:

SELECT T1.[Entry time], T1.Profit, 
 (SELECT Sum(Trades.[Profit]) AS Total

    FROM Trades

    WHERE (Trades.[Entry time] Between CDate([Start Date]) And
   DateAdd("d",1,CDate([End Date]))) AND  
   (Trades.[Entry time]) <= T1.[Entry time]) AS Total


FROM Trades AS T1


ORDER BY T1.[Entry time];

感谢您的协助。

2 个答案:

答案 0 :(得分:1)

您只需要在子查询和外部查询中包含日期条件:

SELECT T1.[Entry time], T1.Profit, 
       (SELECT Sum(Trades.[Profit]) AS Total
        FROM Trades as t2
        WHERE t2.[Entry time] Between t2.[Start Date] And
   DateAdd("d", 1, t2.[End Date]) AND 
               (t2.[Entry time]) <= T1.[Entry time]
       ) AS Total
FROM Trades AS T1
WHERE t1.[Entry time] Between t1.[Start Date] And
                              DateAdd("d", 1, t1.[End Date])
ORDER BY T1.[Entry time];

请注意,我限定了所有列名(包括表引用)。我认为这一点很重要,但在使用相关子查询时更是如此。

答案 1 :(得分:0)

感谢您的回复...通过您给我的内容,我做了几个mod并且能够使它工作......这是最终答案:

SELECT T1.[Entry time], T1.Profit, 
  (SELECT Sum(t2.[Profit]) AS Total
    FROM Trades as t2
    WHERE (t2.[Entry time] Between [Start Date] And
                 DateAdd("d", 1, [End Date])) AND 
                 (t2.[Entry time]) <= T1.[Entry time]
   ) AS Total

FROM Trades AS T1

WHERE (((T1.[Entry time]) Between [Start Date] And DateAdd("d",1,[End Date])))
ORDER BY T1.[Entry time];

再次感谢