I have this SQL Query:
select prefix, code, stat, complete, COUNT(*) as Count
from table
group by prefix, code, stat, complete
order by prefix, code, stat, complete
The column 'prefix' is an alphanumeric value (0-9a-zA-z). What I want is to make it so that if the value of prefix is a number, to make the number equal to 0. If it is a letter, it will keep its value. I have tried to add the following line beneath the group by clause:
(case when prefix like '%[0-9]%' then 0 else prefix end)
But I get an error "Conversion failed when converting the varchar value 'J' to data type int.".
What is causing this error? How can I get the 'prefix' column to display either 0 or a letter?
case when prefix like '%[0-9]%' then '0' else prefix end
You obviously also need this as the expression in the GROUP BY
:
select
NewPrefix = case when prefix like '%[0-9]%' then '0' else prefix end,
code,
stat,
complete,
COUNT(*) as Count
from table
group by
case when prefix like '%[0-9]%' then '0' else prefix end,
code, stat, complete
order by
case when prefix like '%[0-9]%' then '0' else prefix end,
code, stat, complete
Try this :
select case when prefix not like '%[^0-9]%' then prefix else '0' end as prefix, code, stat, complete, COUNT(*) as Count
from table
group by case when prefix not like '%[^0-9]%' then prefix else '0' end, code, stat, complete
order by prefix, code, stat, complete
Check This. Looks similar "ISNUMERIC()"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With