简体   繁体   English

SQL Replace不适用于大于>

[英]SQL Replace Not working for Greater Than >

I'm trying to count all values in a column Value that are over 5. 我试图计算列中的所有值Value是超过5。

However, some results in that column appear like '>10' (it has the greater than symbol > in the field) 然而,一些结果在该列中出现像“> 10”(其具有大于符号>在现场)

I'd like to still count that as > 5. 我仍然认为> 5。

To do that, I did the following: 为此,我做了以下工作:

(COUNT(CASE WHEN t.VALUE LIKE '*>*'
        and Replace(t.VALUE, '>', ' ') > 5)
Then 1
Else NULL
End
)

But, for whatever reason, it's not replacing. 但是,无论出于何种原因,它都不能替代。

Well, how about converting to a number? 那么,如何转换为数字呢?

select sum(case when try_convert(int, replace(t.value, '>', '')) > 5
                then 1 else 0
           end) as values_over_5

Your data model is suspicious, because you are doing numeric comparisons on a column that contains numbers. 您的数据模型是可疑的,因为您正在对包含数字的列进行数字比较。

A couple of things. 有几件事。

The asterisk isn't a valid wildcard character in SQL Server, so we'll change that. 星号不是SQL Server中的有效通配符,因此我们将对其进行更改。

Also, if you want the string to become a number, you'll want to replace the greater-than with an empty string, not a space. 另外,如果您希望字符串变成数字,则需要用空字符串而不是空格代替大号。 It doesn't affect the outcome, but it's the right thing to do. 它不会影响结果,但这是正确的事情。

This isn't as elegant as Gordon's one-liner, but it produced the expected results. 这并不像戈登的单线纸那样优雅,但是却产生了预期的结果。

DECLARE @t TABLE (VALUE VARCHAR(5));
INSERT @t (VALUE)
VALUES ('1'),('10'),('>10');

SELECT COUNT(*) AS Over5
FROM
  (
    SELECT
     CASE WHEN t.VALUE LIKE '%>%' THEN Replace(t.VALUE, '>', '')
         ELSE t.VALUE
     END AS NewVal
    FROM @t as t
  ) AS d
WHERE NewVal > 5;

+-------+
| Over5 |
+-------+
|     2 |
+-------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM