我有一个具有整数和非整数值的列名的表测试。
+------------+
| names |
+------------+
| 123 |
| 123abc |
| 89 |
| dkkjdk |
| dkdn |
+------------+我想在一行中显示整数和非整数值的计数,如下所示
integer_count non_integer_count
2 3我尝试使用此查询打印整数值。
select cast(names as signed) as int_val from test;但我得到了这个结果
+---------+
| int_val |
+---------+
| 123 |
| 123 |
| 89 |
| 0 |
| 0 |
+---------+name字段是varchar(20)字段。
发布于 2015-02-18 05:52:12
这是解决办法
SELECT COUNT(CASE WHEN not names REGEXP '^[0-9]+$' THEN 1 END) AS ALPHA, COUNT(CASE WHEN names REGEXP '^[0-9]+$' THEN 1 END) AS DIGIT FROM test;输出
+-------+-------+
| ALPHA | DIGIT |
+-------+-------+
| 3 | 2 |
+-------+-------+发布于 2014-08-20 07:47:59
使用基于regex的条件之和:
select
sum(names rlike '^[0-9]+$') integer_count,
sum(names not rlike '^[0-9]+$') non_integer_count
from test请参阅SQLFiddle
一些解释:
rlike是like的regex版本^[0-9]+$就匹配。注意^和$,如果没有它们,它将测试值中任何位置的数字。sum(condition)计算条件为真的次数,因为(在mysql中) true为1,false为0发布于 2014-08-20 07:46:03
您可以使用对replace的10次调用来获得没有数字的名称。然后,您可以通过比较名称的长度和没有数字的名称来计算数字数:
select names
, length(names) - length(non_digit) as digit_chars
, length(non_digit) as non_digit_chars
from (
select replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
names, '0', ''),
'1', ''),
'2', ''),
'3', ''),
'4', ''),
'5', ''),
'6', ''),
'7', ''),
'8', ''),
'9', '') as non_digit
, names
from YourTable
) as SubQueryAliashttps://stackoverflow.com/questions/25399214
复制相似问题