当我运行以下查询时,我收到错误“无法将VARCHAR转换为FLOAT”。问题是我的团队中的其他人设计了DB一段时间,并将毫秒作为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
答案 0 :(得分: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答案 1 :(得分:-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