我想得到它们不是过期日期的价值总和
过期日期公式:DATEADD(DAY,VIP.vipValue,[transaction].tDate)
where子句必须是这样的:
DATEDIFF(DAY,GETDATE(),DATEADD(DAY,VIP.vipValue,[transaction].tDate)) > 0
我试试这个:
SELECT SUM(v.vipValue)
FROM [transaction] AS t LEFT JOIN
VIP AS v ON v.vipId = t.vipId
WHERE DATEDIFF(DAY,GETDATE(),DATEADD(DAY,v.vipValue,t.tDate)) > 0
但是它返回null和空结果;但是,如果我将v.vipValue
(例如:30)的某个数字编入,我得到了真实的结果。为什么v.vipValue
有问题?我错在哪里?
答案 0 :(得分:1)
根据评论,v。[timeout]应该用于与日期差异而不是v.vipValue进行比较。
使用表变量的示例代码:
declare @transaction table (tId int identity(1,1), vipId int, tDate date);
declare @VIP table (vipId int, vipValue int, [timeout] int);
insert into @VIP (vipId, vipValue, [timeout]) values (1,1,1), (2,2,20), (3,3,30);
insert into @transaction (vipId, tDate) values (1,getDate()-1), (2,getDate()-1), (3,getDate()-1), (4,getDate()-1);
SELECT t.*, v.vipValue, v.[timeout], DATEDIFF(DAY,t.tDate,GETDATE()) as DayDiff
FROM @transaction AS t
LEFT JOIN @VIP AS v ON v.vipId = t.vipId;
SELECT SUM(v.vipValue)
FROM @transaction AS t
JOIN @VIP AS v ON v.vipId = t.vipId
WHERE v.[timeout] > DATEDIFF(DAY,t.tDate,GETDATE());
第二个查询将返回5