当前位置: 代码迷 >> SQL >> SQLServer处置行转列和列转行
  详细解决方案

SQLServer处置行转列和列转行

热度:100   发布时间:2016-05-05 09:56:14.0
SQLServer处理行转列和列转行

掌握SQL Server 行转列和列转行

1、列转行

      数据经过计算加工后会直接生成前端图表需要的数据源,但是程序里又需要把该数据经过列转行写入中间表中,下次再查询该数据时直接从中间表查询数据。

1.1 列换行语法

复制代码
table_sourceUNPIVOT(value_columnFOR pivot_columnIN(<column_list>))
复制代码

 

1.2  行转列案例

复制代码
WITH TAS(    SELECT 1 as TeamId,'测试团队1' as Team,80 'MEN',20 'WOMEN'    UNION     SELECT 2 as TeamId,'测试团队2' as Team,30 'MEN',70 'WOMEN' )---列转行------------------------------------SELECT TeamId,Team ,TYPE=ATTRIBUTE,CNT=VALUEFROM T UNPIVOT (  VALUE FOR ATTRIBUTE IN ([MEN],[WOMEN])) AS UPV
复制代码

 

2、 行转列

       行转列主要是从中间表里查询数据,SQL SERVER2005以下的版本则可以使用聚合函数来完成。

2.1 行转列语法

复制代码
table_sourcePIVOT(聚合函数(value_column)FOR pivot_columnIN(<column_list>))
复制代码

2.2、使用PIVOT实现

复制代码
WITH TAS(  SELECT  1 AS ID,'测试团队1' TEAM,'MEN' ITEM,80 CENT  UNION  SELECT  1 AS ID,'测试团队1' TEAM,'WOMEN' ITEM,20 CENT  UNION  SELECT  2 AS ID,'测试团队2' TEAM,'MEN' ITEM,30 CENT  UNION  SELECT  2 AS ID,'测试团队2' TEAM,'WOMEN' ITEM,70 CENT)SELECT * FROM T PIVOT (SUM(CENT) FOR ITEM IN ([MEN],[WOMEN])) A
复制代码

2.3、使用聚合函数实现

复制代码
WITH TAS(  SELECT  1 AS ID,'测试团队1' TEAM,'MEN' ITEM,80 CENT  UNION  SELECT  1 AS ID,'测试团队1' TEAM,'WOMEN' ITEM,20 CENT  UNION  SELECT  2 AS ID,'测试团队2' TEAM,'MEN' ITEM,30 CENT  UNION  SELECT  2 AS ID,'测试团队2' TEAM,'WOMEN' ITEM,70 CENT)SELECT ID,TEAM,SUM(CASE WHEN ITEM='MEN' THEN CENT ELSE 0 END) 'MEN',SUM(CASE WHEN ITEM='WOMEN' THEN CENT ELSE 0 END) 'WOMEN' FROM TGROUP BY ID,TEAM
复制代码

 

参考资料

http://www.cnblogs.com/zhangzt/archive/2010/07/29/1787825.html

http://www.cnblogs.com/aspnethot/articles/1762665.html

  相关解决方案