/**
题目:
表A:
Year Month Count
1991 1 1.1
1991 2 1.2
1991 3 1.2
1991 4 1.4
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4
设计SQL语句,使执行结果为:
Year M1 M2 M3 M4
1991 1.1 1.2 1.2 1.4
1992 2.1 2.2 2.3 2.4
1、表说明:表A所有列都是字符串儿类型(varchar(10))
2、解答(执行环境sql server 2008不保证其他环境有效)
方法一:
table_source
PIVOT(
聚合函数(value_column)
FOR pivot_column
IN(<column_list>)
)
方法二:
--pivot_colnum判断列,column_value判断值,print_value符合条件的输出值
CASE pivot_colnum WHEN column_value THEN print_value END
*/
SELECT * FROM dbo.A
--方法1
SELECT * FROM dbo.A pivot(max(A.[Count]) for A.[Month] IN ([1],[2],[3],[4])) AS B
--方法2
SELECT A.[Year] AS [Year],
MAX(CASE A.[Month] WHEN '1' THEN A.[Count] END) AS M1,
MAX(CASE A.[Month] WHEN '2' THEN A.[Count] END) AS M2,
MAX(CASE A.[Month] WHEN '3' THEN A.[Count] END) AS M3,
MAX(CASE A.[Month] WHEN '4' THEN A.[Count] END) AS M4 FROM dbo.A GROUP BY A.[year]
举一反三:行转列,可用:UNPIVOT,用法同PIVOT