Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY multiple values in same column

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?

like image 275
Ultracoustic Avatar asked Jul 18 '14 00:07

Ultracoustic


2 Answers

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
like image 100
Mitch Wheat Avatar answered Sep 23 '22 19:09

Mitch Wheat


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()"

like image 21
Recursive Avatar answered Sep 23 '22 19:09

Recursive