获取天数余额为负

时间:2019-05-31 09:26:39

标签: sql-server

我想获得帐户余额为负的天数。

我有以下余额表。

|AccNo |    Amount      | Date
------------------------------------
|1     |    -8775.76    | 2019-05-31 
|1     |    -697.05     | 2019-05-30
|1     |    -3504.52    | 2019-05-29
|1     |   +1783.67     | 2019-05-28
|1     |    -14204.55   | 2019-05-27


  SELECT DATEDIFF(DAY, AccountB.Date, GETDATE()) AS DaysInDebit
  FROM (SELECT TOP 1 Date
        FROM Balance WHERE AccNo = 1
        AND Amount > 0
        ORDER BY Date DESC
       ) AS AccountB
  ORDER BY AccountB.Date DESC

我希望该帐户有3天的债务。 结果集从2019-05-28到2019-05-31。日期差= 3

2 个答案:

答案 0 :(得分:0)

尝试一下-

SELECT 
DATEDIFF
(
    DD,
    (
        SELECT 
        MAX(Date) 
        FROM your_table 
        WHERE ID= 1
        AND Amount > 0
    ),
    GETDATE()
)
FROM your_table 
WHERE ID = 1
GROUP BY ID 

答案 1 :(得分:0)

您可以通过找到上一个正余额的max()来实现。

select
    count(*) as NumberOfDays
from Balance
where [Date] > (select max([Date]) from Balance where Amount > 0 and AccNo = 1)
and AccNo = 1