SQL 查询将列转换为行

SQL Query Convert columns to rows

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

我们可以通过pivot/unpivot函数得到吗?

使用union all:

select 'total cases' info, sum(cases) cnt from metrics
union all select 'total deaths', sum(deaths) from metrics

或者,如果您的数据库支持横向连接:

select x.info, sum(x.cnt) cnt
from metrics m
cross join lateral (values ('total cases', m.cases), ('total deaths', m.deaths)) as x(info, cnt)
group by x.info

最简单的通用方法是 union all:

select 'Total Cases'  as which, sum(cases) 
from [myschema].[metrics]
union all
select 'Total Deaths' as which, sum(deaths)
from [myschema].[metrics];

方括号看起来像 SQL 服务器。在这种情况下,我建议使用横向连接:

select v.*
from (select sum(cases) as TotalCases, sum(deaths) as TotalDeaths 
      from [myschema].[metrics]
     ) m cross apply
     (values ('TotalCases', TotalCases), ('TotalDeaths', TotalDeaths)
     ) v(which, cnt);

这只读取 table 一次。如果 table 确实是一个更复杂的查询(例如视图或 CTE),性能提升可能会很大。

您也可以使用 UNPIVOT 获得所需的结果:

   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 ) );
     

上面的输出将是:

Category                Value
Total_cases             1234
Total_deaths            123