我有一个令我困惑的SQL查询,基本上我可以使用信用表来表示可以应用和扣除信用,简单,当我引入应用信用的到期日时,它变得棘手我几乎要翻转日期,基本表格如下:
CreditID int Credit int AppliedDate DateTime ExpiryDate DateTime
数据输入的示例如下:
CredidID | Credit | AppliedDate | ExpiryDate ---------+--------+-------------+----------- 1 | 10 | | 1/8/2017 (10 credit added that expire) 2 | 10 | | 1/1/2018 (10 credit added that expire) 3 | -5 | 1/9/2017 | (5 credits used on 1/9)
所以答案就是我目前的学分,5,但是随着表格变得越来越复杂,我无法想到一个sql查询,它可以在任何给定的时间给我今天的信用余额? / p>
任何帮助都将不胜感激。
答案 0 :(得分:1)
如果我必须通过数据库(仅当我必须;)),我会做两个表,一个有余额,第二个有一个信用操作。
例如(在MSSQL中):
create table WalletBalance
(
WalletID bigint identity(1,1) not null primary key,
LastModifiedTime datetime,
Balance bigint
)
create table CreditsOperation
(
ID bigint identity(1,1) not null primary key,
WalletID bigint,
ExpirationDate date,
ModifiedTime datetime
foreign key (WalletID) references WalletBalance(WalletID)
)
然后触发更新,删除和插入操作表,这将增加或减少钱包余额。
然后 - 我会做一个日常的SQL工作,它将执行检查到期日期的程序等。
答案 1 :(得分:1)
select sum(credit) + (select isnull(sum(credit),0) from credits
where AppliedDate is not null
and AppliedDate >
(select isnull(max(ExpiryDate),0) from Credits
where ExpiryDate < getdate() and ExpiryDate is not null))
'Credit Balance'
from credits where ExpiryDate > getdate() and ExpiryDate is not null
逻辑电 1.获得应用学分后的扣除学分总和(已过期的申请学分,即
这个(1 + 2)的总和会得到结果(总结上面的结果,因为在表中带有负值)
如果您仍然失败,请告诉我。
答案 2 :(得分:0)
如果您的应用信用总是负数,那么您可以使用:
SELECT SUM(t.Credit) FROM [yourtable] t
WHERE ExpiryDate IS NULL OR ExpiryDate > GetDate()