2017-10-15 32 views
2

我一直想写一个case语句如下SQL Server - 为什么calc给0?

case when datediff(week,cast(cast(tourney_date as char(8)) as date, current_timestamp) >104 then 0 
    when datediff(week,cast(cast(tourney_date as char(8)) as date, current_timestamp) <=13 then 1 
    when datediff(week,cast(cast(tourney_date as char(8)) as date, current_timestamp) between 14 and 104 
    then cast(((datediff(week,cast(cast(tourney_date as char(8)) as date, current_timestamp)-13)/91) as numeric(6,5) end as multiplier 

但是这不会返回非0.0000值时,DATEDIFF返回14和104之间的值来测试这一点,我试图让一个真正的基本测试上班

declare @test as numeric(6,5) 
set @test=72/91 
print @test 

我还是得到0.00000?我正在犯什么小错误?

在此先感谢。

+0

尝试这个代替 声明@test为数字(6 ,5) set @ test = 72.0/91.0 – Harry

+0

谢谢解释测试,但任何想法为什么案件不起作用? – thequadge

回答

1

错误是integer division

如果整数被除数由整数除数划分,结果是具有这样的结果截断的任何小数部分的整数。

DATEDIFF(week,@datetime,@datetime)返回整数。

您在这里可能会遇到问题,因为您在之前将划分为数值。或者,这是因为SQL Server发现CASE表达式的两个输出是整数,所以它使整个列成为一个整数。请记住,列只能获得一种数据类型。

尝试:

case when datediff(week,cast(cast(tourney_date as char(8)) as date), current_timestamp) >104 then 0.0 
    when datediff(week,cast(cast(tourney_date as char(8)) as date), current_timestamp) <=13 then 1.0 
    when datediff(week,cast(cast(tourney_date as char(8)) as date), current_timestamp) between 14 and 104 
    then cast(((datediff(week,cast(cast(tourney_date as char(8)) as date), current_timestamp)-13.0)/91.0) as numeric(6,5)) end as multiplier 

我试图修复丢失的括号,但可能已经错过了一些。

另外:我可以揣测的唯一原因是cast(cast(tourney_date as char(8)) as date)是因为tourney_date还不是datedatetime。为了上帝的缘故,将日期存储为日期,而不是字符串或数字。

0

你可以把它简单通过这样

declare @tourney_date datetime = '2017-9-16 ' 
declare @new_date datetime = (select DATEADD(day, DATEDIFF(day, 0, @tourney_date), 0)) 
select 
case when datediff(week,@new_date, current_timestamp) >104 then 0 
    when datediff(week,@new_date, current_timestamp) <=13 then 1 
    when datediff(week,@new_date, current_timestamp) between 14 and 104 
    then cast(((datediff(week,@new_date, current_timestamp)-13)/91.0) as numeric(6,5)) end as multiplier 
0

做的事情在SQL Server中,当你师九十一分之七十二它的平均INT/INT结果为int。

实施例:(INT)0.79120 = 0

可以尝试:

declare @test as numeric(6,5) 
set @test=CAST(72 AS DECIMAL(5,1))/91 
select @test union all 
select 72.0/91 union all 
select (72*1.0)/91 

在这里可以看到的更多信息:SQL Server division query