我有 4 列带有 Sum 和 Count 函数。我想将 4 列转换为 4 行

I have 4 columns with Sum and Count Functions. I want to convert 4 columns in 4 rows

我使用了这个查询

Select Count(PostID) As TotalPost,sum(Impressions) As TotalImpression, sum(Likes) As TotalLikes, Sum(Shares) As Shares, Sum(Engagements)AS Engagements
From dm.vSocialMediaPost;

结果:

TotalPost TotalImpression TotalLikes   Shares  Engagements
712      |  1874273      |  29418     | 4231|   65326

我想要这样的结果

TotalPost             |712
TotalImpression       | 1874273      
TotalLikes            |29418  
Shares                |4231
Engagements           |65326

一个选项是联合查询:

SELECT 'TotalPost' AS label, COUNT(*) AS total FROM dm.vSocialMediaPost
UNION ALL
SELECT 'TotalImpression', SUM(Impressions) FROM dm.vSocialMediaPost
UNION ALL
SELECT 'TotalLikes', SUM(Likes) FROM dm.vSocialMediaPost
UNION ALL
SELECT 'Shares', SUM(Shares) FROM dm.vSocialMediaPost
UNION ALL
SELECT 'Engagements', SUM(Engagements) FROM dm.vSocialMediaPost;

最简单的方法是多次聚合:

Select 'TotalPost', count(*)
From dm.vSocialMediaPost
union all
select 'TotalImpression', sum(Impressions)
From dm.vSocialMediaPost
union all
select 'TotalLikes', sum(Likes)
From dm.vSocialMediaPost
union all 
select 'Shares', Sum(Shares)
From dm.vSocialMediaPost
union all
select 'Engagements', Sum(Engagements)
From dm.vSocialMediaPost; 

但是,由于SQL服务器支持横向连接,最好的方法是apply:

select v.*
from (select Count(PostID) As TotalPost, sum(Impressions) As TotalImpression, sum(Likes) As TotalLikes, Sum(Shares) As Shares, Sum(Engagements) as Engagements
      from dm.vSocialMediaPost
     ) x cross apply
     (values ('TotalPost', TotalPost),
             ('TotalImpression', TotalImpression),
             ('TotalLikes', TotalLikes),
             ('Shares', Shares),
             ('Engagements', Engagements)
     ) v(which, val);

这是 "best",因为它只需要聚合(并因此读取)table 一次。它应该比多次聚合快得多。

您可以使用 unpivot 关键字作为 :

select title, value 
  from
     ( Select Count(PostID) As TotalPost,
              sum(Impressions) As TotalImpression, 
              sum(Likes) As TotalLikes, 
              Sum(Shares) As Shares, 
              Sum(Engagements)AS Engagements
         From vSocialMediaPost ) p
unpivot  
   (value for Title in
      (TotalPost, TotalImpression, TotalLikes, Shares, Engagements)  
) unpvt;

Rextester Demo