如何在SQL Server中水平旋转表

前端之家收集整理的这篇文章主要介绍了如何在SQL Server中水平旋转表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有列的表格如下:
  1. Sr.no Subject No of class attended
  2. -------------------------------------
  3. 1 English 3
  4. 2 Maths 4
  5. 3 SocialScience 5

我希望这种格式的表格

  1. English Maths SocialScience
  2. ---------------------------------
  3. 3 4 5

我试过这个:

  1. Select case when subject ='Maths' then COUNT(No_of_Candidates) else null end as Maths

但有了这个,我得到这样的数据:

  1. English Maths SocialScience
  2. ---------------------------------
  3. 3
  4. 4
  5. 5

请帮帮我怎么解决这个问题..

解决方法

正如你所说,你不希望输出像这样:
  1. English Maths SocialScience
  2. ---------------------------------
  3. 3
  4. 4
  5. 5

您需要使用这样的子查询

  1. SELECT English,Maths,SocialScience
  2. FROM (
  3. SELECT Subject,No_of_class_attended
  4. FROM mytable) up
  5. PIVOT
  6. (Sum([No_of_class_attended])
  7. for Subject in ([English],[Maths],[SocialScience])) p

输出

  1. English Maths SocialScience
  2. ---------------------------------
  3. 3 4 5

See this SQLFiddle

欲了解更多,请参阅SQL SERVER – PIVOT and UNPIVOT Table Examples

猜你在找的MsSQL相关文章