SQL查询:转换

时间:2014-07-27 14:12:32

标签: sql sql-server r postgresql sqldf

我正在尝试使用SQL查询从数据库中读取列。该列由空字符串或数字组成的字符串,例如

"7500" "4460" "" "2900" "2640" "1850" "" "2570" "9050" "8000" "9600"

我正在尝试找到正确的sql查询来提取所有数字(作为整数)并删除空数字,但我被卡住了。到目前为止我已经

SELECT * 
FROM   base 
WHERE  CONVERT(INT, code) IS NOT NULL

在程序R(包sqldf)中完成

4 个答案:

答案 0 :(得分:1)

如果所有列都是有效整数,则可以使用:

select * , cast(code as int) IntCode
from base 
where code <> ''

要防止字段code不是有效数字的情况,请使用:

select *, cast(codeN as int) IntCode
from base
cross apply (select case when code <> '' and not code like '%[^0-9]%' then code else NULL end) N(codeN)
where codeN is not null

SQL Fiddle

<强>更新

要查找代码不是有效数字的行,请使用

select * from base where code like '%[^0-9]%'

答案 1 :(得分:0)

select *
from base
where col like '[1-9]%'

示例:http://sqlfiddle.com/#!6/f7626/2/0

如果您不需要测试有效的数字,即。一个字符串,如'909XY2'那么这可能会略微加快,或多或少取决于表的大小

答案 2 :(得分:0)

这是你想要的吗?

SELECT (case when code not like '%[^0-9]%' then cast(code as int) end)
FROM   base 
WHERE code <> '' and code not like '%[^0-9]%'; 

有意在wherecase重复这些条件。 SQL Server不保证在where中的逻辑之前应用select过滤器,因此转换时可能会出错。更新版本的SQL Server有try_convert()来解决此问题。

答案 3 :(得分:0)

将sqldf与默认的sqlite数据库和此测试数据一起使用:

 DF <- data.frame(a = c("7500", "4460", "", "2900", "2640", "1850", "", "2570", 
                        "9050", "8000", "9600"), stringsAsFactors = FALSE)

试试这个:

library(sqldf)
sqldf("select cast(a as aint) as aint from DF where length(a) > 0")

,并提供:

  aint
1 7500
2 4460
3 2900
4 2640
5 1850
6 2570
7 9050
8 8000
9 9600

注意在普通R中,可以写:

transform(subset(DF, nchar(a) > 0), a = as.integer(a))