Please, When i am using the statement, SELECT location, date, total_cases, total_deaths, (total_deaths /total_cases) FROM CovidPortfolioProject..coviddeaths I'm getting an error

Brenan ADAOBI 20 Reputation points
2023-05-25T21:54:03.9033333+00:00

When I execute this code below,

I get the error Msg 8117, Level 16, State 1, Line 17 Operand data type nvarchar is invalid for divide operator.

select location, date, total_cases, total_deaths, (total_deaths / total_cases)*100 as DeathPercent

from ProjectPortfolio..CovidDeaths

order by 1,2

What can I do to move forward? I am in transition into data analysis.

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,808 questions
0 comments No comments
{count} votes

Accepted answer
  1. CosmogHong-MSFT 23,321 Reputation points Microsoft Vendor
    2023-05-26T01:48:17.35+00:00

    Hi @Brenan ADAOBI

    Operand data type nvarchar is invalid for divide operator.

    The error message you got is clear enough. You can apply divide calculation only on numeric data, not on string value. It seems that total_deaths or total_cases are Nvarchar type. You may have to convert the strings to numeric first.

    Try this:

    select location, date, total_cases, total_deaths, (CONVERT(DECIMAL(18,2), total_deaths) / CONVERT(DECIMAL(18,2), total_cases) )*100 as DeathPercent
    from ProjectPortfolio..CovidDeaths
    order by 1,2
    

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    4 people found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Naomi 7,361 Reputation points
    2023-05-25T22:18:16.11+00:00

    Try the following:

    select location, date, total_cases, total_deaths, (try_cast(total_deaths as decimal(12,2)) / NULLIIF(try_cast(total_cases as int),0))*100 as DeathPercent
    from ProjectPortfolio..CovidDeaths
    order by 1,2
    
    1 person found this answer helpful.