我一直在尝试编写一个案例陈述,如下所示
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
然而,当datediff返回14到104之间的值时,这不会返回非0.0000值。为了测试这个,我试图让一个非常基本的测试工作
declare @test as numeric(6,5)
set @test=72/91
print @test
我仍然得到0.00000?我犯了什么基本错误?
提前致谢。
答案 0 :(得分:1)
错误是integer division:
如果整数被除数除以整数除数,则结果是一个整数,其截断结果的任何小数部分。
global._ = _;
返回一个整数。
你在这里遇到问题可能是因为你在之前将划分为数字值。或者,这是因为SQL Server发现CASE表达式的两个输出是整数,因此它使整个列成为整数。请记住,列只能获得一种数据类型。
尝试:
DATEDIFF(week,@datetime,@datetime)
我试图修复你丢失的括号,但可能错过了一些。
另外:我可以理解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
或date
。为了上帝的缘故,将日期存储为日期,而不是字符串或数字。
答案 1 :(得分: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
答案 2 :(得分:0)
在Sql Server中,当你划分72/91时,它的意思是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