0

当我运行以下查询时,我收到错误“无法将 VARCHAR 转换为 FLOAT”。问题是我团队中的其他人不久前设计了数据库并将毫秒作为 varchar 和 sSometime 值不存在,所以他改为使用“NA”。

现在,当我将毫秒值转换为 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
4

2 回答 2

6

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

如果您希望将这些NA值一起排除,那么您将执行以下操作:

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 with Demo

于 2012-07-25T21:08:48.270 回答
-1

使用案例...例如...

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
于 2012-07-25T21:09:46.453 回答