問題描述
我有這個 SQL 查詢:
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
前綴"列是一個字母數字值 (0-9a-zA-z).我想要的是讓它如果前綴的值是一個數字,使數字等于0.如果它是一個字母,它會保持它的值.我試圖在 group by 子句下面添加以下行:
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)
但我收到錯誤消息將 varchar 值 'J' 轉換為數據類型 int 時轉換失敗.".
But I get an error "Conversion failed when converting the varchar value 'J' to data type int.".
是什么導致了這個錯誤?如何讓前綴"列顯示 0 或一個字母?
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
你顯然也需要這個作為 GROUP BY
中的表達式:
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
這篇關于GROUP BY 同一列中的多個值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!