SQL语句Where子句不将varchar与十进制值

时间:2016-01-29 13:17:09

标签: sql-server

表在SQLServer 2008中显示如下输出

Sno Currency     Val1          Val2
1   PLN          309471355.4   228185914.7
2   USD          0.00000000    0.00000000

我需要跳过值为0的记录。尝试转换Cost列但返回错误。

PLS。在SQL查询下面找到

Select 
Sum(curr) as 'Cost',
sum(val) as 'Val1'
From Table
Where
Cast('Cost' as int) >1

将错误消息返回为

  

错误消息转换失败转换varchar值'成本'   数据类型int。

感谢任何过滤该记录的建议。

1 个答案:

答案 0 :(得分:0)

执行此操作时:

Cast('Cost' as int) >1

它会尝试投放varchar'费用'到一个int。哪个不起作用

您需要执行子查询以总结该值。像这样:

SELECT
    *
FROM
(
    Select 
        Sum(curr) as Cost,
        sum(val) as Val1
    From 
        Table
) AS tbl
Where
    tbl.Cost >1

或者您也可以使用HAVING这样做:

Select 
    Sum(curr) as Cost,
    sum(val) as Val1
From 
    Table
HAVING Sum(curr)>1

但听起来你甚至没有什么总和。你只想把文件丢掉0.所以为什么不这样做呢:

SELECT * FROM Table where NOT table.val=0