我在从借方贷方记录中获取余额时遇到问题。但是在我的表中日期是相同的,但借方贷方是不同的。
declare @StartDate Datetime = '2018-11-03';
declare @EndDate Datetime = '2018-11-03';
Select
y.Description,
y.DateTime,
y.Credit,
y.Debit,
SUM(ISNULL(x.Debit, 0) - ISNULL(x.Credit, 0)) AS Balance
FROM Accounts x
INNER JOIN Accounts y ON x.DateTime <= y.DateTime
WHERE
CONVERT(date, y.DateTime) >= CONVERT(date, @StartDate)
AND
CONVERT(date, y.DateTime) <= CONVERT(date, @EndDate)
GROUP BY
y.DateTime,
y.Credit,
y.Debit,
y.Description
Order By
y.DateTime
我的结果不是我想要的。
答案 0 :(得分:2)
您可以通过使用窗口功能来实现
select
DateTime,
Credit,
Debit,
(select sum(Debit - Credit) from Account a where a.Datetime < t.DateTime) +
Sum(Debit - Credit) Over (Order by DateTime) balance
from Account t
答案 1 :(得分:1)
如果我正确阅读了您的问题和评论,这就是您想要的:
declare @StartDate Datetime = '2017-11-03';
declare @EndDate Datetime = '2019-11-03';
Select DateTime, Credit, Debit
, -- Get the prior Balance
(select sum(ISNULL(Debit, 0) - ISNULL(Credit, 0))
from Account p
where CONVERT(date, p.DateTime) < CONVERT(date, @StartDate))
-- and add it to the running total
+ sum(ISNULL(t.Debit, 0) - ISNULL(t.Credit, 0))
over (order by DateTime, id) Balance
from Account T
where CONVERT(date, DateTime) >= CONVERT(date, @StartDate)
and CONVERT(date, DateTime) <= CONVERT(date, @EndDate)
order by DateTime, ID
答案 2 :(得分:0)
USE [YourDataBase]
GO
/****** Object: StoredProcedure [dbo].[Balance_Sheet] Script Date: 5/16/2019 3:13:53 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Balance_Sheet]
@StartDate datetime,
@EndDate datetime
AS
BEGIN
Select
x.DateTime,
x.Comments,
x.Credit,
x.Debit,
SUM(coalesce(y.Credit, 0) - coalesce(y.Debit, 0)) AS Balance
FROM Balance x
INNER JOIN Balance y
ON y.DateTime <= x.DateTime
where x.DateTime >=dateadd(day,datediff(day,0,@StartDate),0) and x.DateTime<dateadd(day,datediff(day,0,@EndDate)+1,0)
GROUP BY
x.DateTime,
x.Credit,
x.Debit,
x.Comments
END