2017-10-15 71 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