你可以在SQL Server Management Studio中对nvarchar列类型使用”/”运算符吗?

huangapple go评论64阅读模式
英文:

Can I use "/" operator on nvarchar column type in SQL Server Management Studio?

问题

我试图将两列进行除法运算,这两列被定义为nvarchar,但是SQL Server Management Studio(SSMS)抛出错误,指出无法在nvarchar上使用/运算符。

select 
    location, date, total_cases, total_deaths, 
    (total_deaths / total_cases) * 100
from 
    CovidDeaths#xlsx$
order by 
    1, 2

我无法对total_casestotal_deaths进行除法运算。

英文:

I am trying to divide 2 columns which are defined as nvarchar, but SSMS throws an error saying you can not use / operator on nvarchar.

select 
    location, date, total_cases, total_deaths, 
    (total_deaths / total_cases) * 100
from 
    CovidDeaths#xlsx$
order by 
    1, 2

I am unable to divide the total_cases and total_deaths.

答案1

得分: 2

请尝试以下更改,因为您无法将 "string" 值进行除法运算。请考虑将其转换或强制转换为十进制值。我假设我的回答中的 total_cases 不为零。

select 
    location, 
    date, 
    total_cases, 
    total_deaths, 
    CONVERT(DECIMAL(18, 2), (CONVERT(DECIMAL(18, 2), total_deaths) / CONVERT(DECIMAL(18, 2), total_cases))) as [DeathsOverTotal]
from CovidDeaths#xlsx$
order by 1,2
英文:

Try the following instead since you cannot divide "string" values. Consider converting or casting to a decimal value. I'm assuming total_cases is nonzero in my answer.

select 
    location, 
    date, 
    total_cases, 
    total_deaths, 
    CONVERT(DECIMAL(18, 2), (CONVERT(DECIMAL(18, 2), total_deaths) / CONVERT(DECIMAL(18, 2), total_cases))) as [DeathsOverTotal]
from CovidDeaths#xlsx$
order by 1,2

huangapple
  • 本文由 发表于 2023年3月21日 03:08:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75794352-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定