2012-07-25 80 views
0

當我運行以下查詢時,出現錯誤「無法將VARCHAR轉換爲FLOAT」。問題是我的團隊中的其他人在設計數據庫的同時,將毫秒數作爲varchar和sSometime設置爲不存在,因此他將「NA」代替。SQL Conditional Cast VARCHAR for FLOAT

現在,當我將毫秒數值轉換爲AVE()時,「NA」不能被轉換。有沒有辦法來定義「NA」默認值,如:

IF a.Milliseconds == "NA" 
    0 
ELSE 
    CAST(a.Milliseconds AS FLOAT) 



SELECT 
    b.Date, 
    AVG(CAST(a.Milliseconds AS FLOAT)) AS Milliseconds, 
FROM Fields a 
INNER JOIN Cycles b 
ON a.CyclesId = b.Id 
GROUP BY b.Date 

Sample Data 

CyclesId | Milliseconds 
1  | 24.1557 
2  | 23.4886 
3  | NA 
+0

如果可行,更改表模式以使毫秒爲空的浮點列,並相應地更新應用程序。 – 2012-07-25 21:44:13

回答

6

如果你想排除所有一起NA值,那麼你將做使用CASE聲明在你的價值

SELECT 
    b.Date, 
    AVG(CAST(CASE WHEN a.Milliseconds = 'NA' THEN '0' ELSE a.Milliseconds END AS FLOAT)) AS Milliseconds, 
FROM Fields a 
INNER JOIN Cycles b 
    ON a.CyclesId = b.Id 
GROUP BY b.Date 

以下:

SELECT 
    b.Date, 
    AVG(CAST(a.Milliseconds AS FLOAT)) AS Milliseconds, 
FROM Fields a 
INNER JOIN Cycles b 
    ON a.CyclesId = b.Id 
WHERE a.Milliseconds != 'NA' 
GROUP BY b.Date 

看到SQL Fiddle與演示

+0

我可以將AVE(24.1557,23.4886,NA)修改爲23.82215而不是15.8814333(其來自'NA'取0) – Raza 2012-07-25 23:20:53

+0

請參閱我的編輯,您將不再需要'CASE'並且可以通過' WHERE條款 – Taryn 2012-07-25 23:34:13

-1

使用CASE ...例如...

SELECT 
    b.Date, 
    AVG(CAST((case when a.Milliseconds = 'NA' then 0 else a.Milliseconds end) AS FLOAT)) AS Milliseconds, 
FROM Fields a 
INNER JOIN Cycles b 
ON a.CyclesId = b.Id 
GROUP BY b.Date 
+2

除非您將單引號置於零附近,否則這將不起作用 – Taryn 2012-07-25 21:52:52

+0

並在'NA'之前添加等號... – 2012-07-26 01:12:33