Search code examples
sqlsumpivotunpivot

SQL Query Convert columns to rows


select sum(cases) as [Total cases], sum(deaths) as [Total deaths] 
FROM [myschema].[metrics]

Query output

Can we get by pivot/unpivot function?


Solution

  • You could use UNPIVOT to get the desired result also:

       SELECT
        *
    FROM
        (
            SELECT
                SUM(cases)      AS total_cases,
                SUM(deaths)     AS total_deaths
            FROM
                myschema.metrics
        ) UNPIVOT ( value
            FOR category
        IN ( total_cases,
             total_deaths ) );
         
    

    The output of the above will be:

    Category                Value
    Total_cases             1234
    Total_deaths            123