我有4个带有求和和计数功能的列。我想将4列转换为4行

时间:2018-12-07 11:42:06

标签: sql sql-server unpivot

我使用了此查询

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

3 个答案:

答案 0 :(得分:1)

一个选项是联合查询:

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;

答案 1 :(得分:1)

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

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 Server支持横向联接,所以最好的方法使用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);

这是“最佳”的,因为它只需要汇总(并因此读取)表一次。它应该比多重聚合快得多。

答案 2 :(得分:1)

您可以将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