我如何编写一个查询来计算从另一个表中添加单元格值所需的时间?
例如,在下面的两个表中,我想从表2中的用户A开始借记开始,并从表1开始计算用户A加起来需要多少天(从借方日期开始)表2中的值。
Date User Credits
Apr 30 A 25
Apr 30 B 75
May 1 A 25
May 2 A 25
May 2 B 75
May 3 A 50
May 3 B 75
Date User Debits
May 4 B 150
May 5 A 100
我想从表2中的每个用户的借记值开始,并计算达到该信用额所需的倒退天数(从借记日期开始)。在这种情况下,我寻找用户A的结果是" 5" - 五天达到100.这需要为多个用户服务。用户B的结果应为" 3" - 从5月4日到5月2日的三天到达150.
我对如何开始感到困惑。解决方案是一堆IF语句吗?
示例结果:
Debit Date User Debit Amount Days Back of Credits
4-May B 150 3
5-May A 100 5
答案 0 :(得分:0)
试试这个。
cte
是为了找到累积余额
; with cte as
(
select [User] = t2.[User],
Debit_Date = t2.[Date],
Debit_Amt = t2.[Debits],
Credit_Date = t1.[Date],
Balance = t2.[Debits] - SUM(t1.[Credits]) OVER (PARTITION BY t2.[Date] ORDER BY t1.[Date])
from table2 t2
inner join table1 t1 on t2.[User] = t1.[User]
)
select [User],
Debit_Date,
Debit_Amt,
[Days] = datediff(day, min(Credit_Date), Debit_Date) + 1
from cte
where Balance >= 0
group by [User], Debit_Date, Debit_Amt
答案 1 :(得分:0)
我认为你的日差异是错误的,但是来自表A的两个日期是正确的。
验证我的结果,并测试其他样品日期并告诉我。
declare @TableA table(Dates date,Users varchar(50),Credits int)
insert into @TableA VALUES
('2017-Apr-30','A',25)
,('2017-Apr-30','B',75)
,('2017-May-1 ','A',25)
,('2017-May-2 ','A',25)
,('2017-May-2 ','B',75)
,('2017-May-3 ','A',50)
,('2017-May-3 ','B',75)
declare @TableB table(Dates date,Users varchar(50),Debit int)
insert into @TableB VALUES
('2017-May-4','B',150)
,('2017-May-5','A',100)
;with CTE as
(
select A.Dates,A.Users
,(select sum(A1.Credits) from @TableA A1
where a1.dates<=a.dates
and a1.users=a.users)cr
from @TableA A
)
,CTE1 AS(
select b.Dates [Debit Date],b.Users
,b.Debit [Debit Amount]
,(
select top 1 c.dates
from cte c where
b.Users=c.users and c.cr>=b.Debit
)CreditDates
from @TableB B
)
select [Debit Date],Users,[Debit Amount]
,datediff(day,CreditDates,[Debit Date])[Days Back of Credits]
,CreditDates -- just for test
from cte1