选择Datediff不起作用的地方

时间:2018-01-11 09:29:39

标签: sql sql-server-2008-r2

我有两张桌子。 VIPtransactions
enter image description here

我想得到它们不是过期日期的价值总和 过期日期公式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有问题?我错在哪里?

更新帖子 enter image description here 澄清一下,这些是VIP和交易数据 enter image description here
enter image description here

1 个答案:

答案 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