如何在SQL Server中将行和列切换成行?

时间:2016-05-23 07:32:28

标签: sql sql-server rows

嗨,我有一张如下表,。

Stat                        Points  TeamA TeamB     Date
Highest Total               248     5       387     2016-05-14
Lowest Total                153     2       5       2016-05-11
Highest Successful Chase    195     5       386     2016-05-07
Lowest Score Defended       211     5       4       2016-05-18

我希望结果如,

        Highest Total   Lowest Total    Highest Chase   Low Defended
  A     248             153             195             211     
  B     5               2               5               5   
  C     384             5               386             4   
  D     2016-05-14      2016-05-11      2016-05-07      2016-05-18

帮助我得到结果,我是sql server的新手。

1 个答案:

答案 0 :(得分:1)

无论这个'A','B',......都是真的意思,无论是透视还是透视。 它还显示了向常见varchar(20)投射不同类型的内容。根据您的要求,您可能需要不同的演员阵容。

select rowType,
  max(case ut.stat when 'Highest Total' then value end) as [Highest Total],
  max(case ut.stat when 'Lowest Total' then value end) as [Lowest Total],
  max(case ut.stat when 'Highest Chase' then value end) as [Highest Chase],
  max(case ut.stat when 'Lowest Score Defended' then value end) as [Lowest Defended]
from t
cross apply (
    select * 
    from (
        values 
        ('A', cast(points as varchar(20)), stat),
        ('B', cast(TeamA as varchar(20)), stat),        
        ('C', cast(TeamB as varchar(20)), stat),
        ('D', cast(Date as varchar(20)), stat)
     ) ut(rowType, value, stat) )ut
group by rowType