2014-06-29 58 views
-1

我有这些列的表:计算天客户有余额为零

TransID, CustomerID, Date, Credit, Debit, CurrentBalance 

我想知道有多少天,因为客户有一个明确的平衡已经过去了,因为我不牛逼给予信贷,如果他们没有清理其资产负债在过去的14天,

让我们来谈谈一个特定的客户:现在

TransID, CustomerID, Date,  Credit, Debit, CurrentBalance 
1  1   01/01/2014 0  50  50 
2  1   01/05/2014 50  0  0 
3  1   06/28/2014 0  100 100 

于14年6月29日他们只需1天以来的ir平衡是明确的,但如果我从CurrentBalance = 0的最后一行计算,它是超过175天

+0

你是什么意思“平衡清晰”? –

+0

如果它是“因为余额为'0'”,为什么你不能向有积极余额的人发放信用? –

回答

1

从逻辑上讲,上次余额为零是即时进行的最后一次销售前,当余额为零,这可以通过出售金额等于销售后的余额来确定,即Debit = CurrentBalance - 只有在销售前的余额为零时才会发生这种情况。

select 
    c.id customerid, 
    coalesce(datediff(day, max(t.date), getdate()), 0) days_clear 
from customer c 
left join transaction t on t.CustomerID = c.id 
    and Debit = CurrentBalance 
group by customerid 

使用客户表和左连接到事务表允许的情况下,当客户从来没有做出交易(所以他的天数为零)。

1

这是你在找什么?

select customerid, 
     datediff(day, max(case when balance = 0 then date end), getdate()) 
from table t 
group by customerid; 

这将返回自最近一次0余额记录以来的天数。

编辑:

现在我想我明白了。问题是0天平持续到2014年6月18日。在SQL Server 2012或更高版本,我们可以lead()处理这个问题:

select customerid, 
     datediff(day, max(case when balance = 0 then nextdate end), getdate()) 
from (select t.*, lead(date) over (partition by customerid order by date) as nextdate 
     from table t 
    ) t 
group by customerid; 

牛逼

+0

这会让我回到175天,真的是他只有1天的余额,因为它在过去6个月内没有任何交易 – Nathan11205