简体   繁体   中英

SQL Replace Not working for Greater Than >

I'm trying to count all values in a column Value that are over 5.

However, some results in that column appear like '>10' (it has the greater than symbol > in the field)

I'd like to still count that as > 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.

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 |
+-------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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