-3

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.

6
  • 2
    Of course you can't divide two text values. You might just as well try to divide "foo" / "bar". But you could try cast()-ing the values to some numeric type first. Commented Mar 20, 2023 at 19:16
  • Also, telling us you use Management Studio is like telling us the car you drive is a Sony, because that's the brand you see on the dashboard radio. Fine some of the time, but less helpful when talking to your mechanic about engine trouble. Commented Mar 20, 2023 at 19:17
  • 1
    This is literally the 3rd time I have seen this question in less than 24 hours... 1, 2, 3 Commented Mar 20, 2023 at 19:21
  • 1
    Bad Habits to Kick : ORDER BY ordinal Commented Mar 20, 2023 at 19:36
  • 1
    Store numbers as numbers, and forget about this problem. Commented Mar 20, 2023 at 20:49

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Select location, date, total_cases,total_deaths, (CONVERT(float, total_deaths) / NULLIF(CONVERT(float, total_cases), 0)) * 100 AS Deathpercentage from PortfolioProject..covidDeaths order by 1,2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.