请我是T-SQL的新手,我发现很难实现这个目标。如何保持减去两列以更新列以保存两列之间的差异,从特定日期开始到另一个日期..
答案 0 :(得分:1)
您可以使用Between operator或Datediff function
UPDATE table_name
SET column1 = column2-column3
WHERE dateColumn BETWEEN '01-01-2016' AND '12-31-2016'
答案 1 :(得分:0)
你在寻找跑步总数吗?这说起来容易做起来难,但你需要在当前记录之前递归引用所有记录。看起来像这样:
declare @ledger table (LedgerId int, LedgerDate datetime, Amount decimal(2))
insert into @ledger (LedgerId, LedgerDate, Amount) values
(1, dateadd(hour, -1, getdate()), 1.00),
(2, dateadd(hour, -2, getdate()), 2.00),
(3, dateadd(hour, -3, getdate()), 3.00),
(4, dateadd(hour, -4, getdate()), 4.00),
(5, dateadd(hour, -5, getdate()), 5.00),
(6, dateadd(hour, -6, getdate()), 6.00)
;
declare @startDate datetime = dateadd(hour, -5, getdate()),
@endDate datetime = dateadd(hour, -2, getdate())
;
with orderedByDate as (
select
LedgerId,
LedgerDate,
Amount,
ROW_NUMBER() over (order by LedgerDate desc) rowNum
from @ledger
where LedgerDate between @startDate and @endDate
), runningTotal as (
select
orderedByDate.LedgerId,
max(case when orderedByDate.rowNum = previousValues.rowNum then orderedByDate.LedgerDate else 0 end) LedgerDate,
max(case when orderedByDate.rowNum = previousValues.rowNum then orderedByDate.Amount else 0 end) Amount,
sum(previousValues.Amount) Total
from orderedByDate
inner join orderedByDate previousValues
on orderedByDate.rowNum >= previousValues.rowNum
group by orderedByDate.LedgerId
)
select
LedgerId,
LedgerDate,
Amount,
Total
from runningTotal
这会给你类似的东西:
LedgerId | LedgerDate | Amount | Total
---------|------------|--------|-------
2 |2016-11-03 |2 |2
3 |2016-11-03 |3 |5
4 |2016-11-03 |4 |9
5 |2016-11-03 |5 |14