减去两行相同的表并总结差异

时间:2013-06-20 13:59:05

标签: sql sql-server tsql

OrNo    CurrentDate         PreviousDate        Finished    Amount
G988    02.05.2013 14:00:47 NULL                False       1560
G988    02.05.2013 21:30:00 02.05.2013 14:00:47 False       3170
G988    03.05.2013 06:00:00 02.05.2013 21:30:00 False       5095
G988    03.05.2013 07:46:24 03.05.2013 06:00:00 True        5254

表名:oldDate

我有这些数据,我必须计算一天的总金额,但我还需要减去前一天的金额,以便只计算今天产生的金额(当前日期)。

当前日期是订单处理的实际日期,上一个日期是处理此订单的最后一天。如果我不清楚数据的解释,请指出我,我试过..

if t2.CurrentDate = t1.PreviousDate and datepart(t2.CurrentDate)= datepart(t1.CurrentDate) 

then
     if t1.CurrentDate>t2.CurrentDate

        then  @amount = t1.Amount

     else @amount = t2.Amount

我很难处理连接.. :(所以我对这个逻辑有问题,我尝试了其他一些代码的其他代码,但没有成功,任何想法都会非常感激..

1 个答案:

答案 0 :(得分:3)

如果你能得到一个包含列的表:

  • OrNo
  • CurrDate
  • PrevDate
  • CurrAmount
  • PrevAmount

然后解决你的问题将是微不足道的。给定AnonymousTable,此查询将生成数据:

SELECT a.OrNo,
       a.CurrentDate AS CurrDate, a.PreviousDate AS PrevDate,
       a.Amount AS CurrAmount,    b.Amount AS PrevAmount
  FROM AnonymousTable AS a
  JOIN AnonymousTable AS b
    ON a.OrNo = b.OrNo AND a.PrevDate = b.CurrDate
UNION
SELECT a.OrNo,
       a.CurrentDate AS CurrDate, a.PreviousDate AS PrevDate,
       a.Amount AS CurrAmount,    0 AS PrevAmount
  FROM AnonymousTable AS a
 WHERE a.PreviousDate IS NULL

所以,大概你可以写:

SELECT OrNo, CurrDate, CurrAmount - PrevAmount AS NewAmount
  FROM (SELECT a.OrNo,
               a.CurrentDate AS CurrDate, a.PreviousDate AS PrevDate,
               a.Amount AS CurrAmount,    b.Amount AS PrevAmount
          FROM AnonymousTable AS a
          JOIN AnonymousTable AS b
            ON a.OrNo = b.OrNo AND a.PrevDate = b.CurrDate
        UNION
        SELECT a.OrNo,
               a.CurrentDate AS CurrDate, a.PreviousDate AS PrevDate,
               a.Amount AS CurrAmount,    0 AS PrevAmount
          FROM AnonymousTable AS a
         WHERE a.PreviousDate IS NULL
       )

同样清楚的是,如果你坚持下去,你可以通过写下来简化:

SELECT a.OrNo,
       a.CurrentDate AS CurrDate, a.PreviousDate AS PrevDate,
       a.Amount - b.Amount AS NewAmount
  FROM AnonymousTable AS a
  JOIN AnonymousTable AS b
    ON a.OrNo = b.OrNo AND a.PrevDate = b.CurrDate
UNION
SELECT a.OrNo,
       a.CurrentDate AS CurrDate, a.PreviousDate AS PrevDate,
       a.Amount AS NewAmount
  FROM AnonymousTable AS a
 WHERE a.PreviousDate IS NULL

这里的关键技术是UNION查询和自联接。您的数据具有一致的日期和时间“线程”,因此当前日期和上一个日期列之间的比较是微不足道的。