SQL 查询横表变竖表

 

/*
普通行列转换

假设有张学生成绩表(tb)如下:
Name Subject Result
张三 语文  74
张三 数学  83
张三 物理  93
李四 语文  74
李四 数学  84
李四 物理  94
*/

-------------------------------------------------------------------------
/*
想变成 
姓名         语文        数学        物理          
---------- ----------- ----------- ----------- 
李四         74          84          94
张三         74          83          93
*/

createtable tb
(
   Name    varchar(10) ,
   Subject varchar(10) ,
   Result  int
)

insertinto tb(Name , Subject , Result) values('张三' , '语文' , 74)
insertinto tb(Name , Subject , Result) values('张三' , '数学' , 83)
insertinto tb(Name , Subject , Result) values('张三' , '物理' , 93)
insertinto tb(Name , Subject , Result) values('李四' , '语文' , 74)
insertinto tb(Name , Subject , Result) values('李四' , '数学' , 84)
insertinto tb(Name , Subject , Result) values('李四' , '物理' , 94)
go

--静态SQL,指subject只有语文、数学、物理这三门课程。
select name 姓名,
  max(case subject when'语文'then result else0end) 语文,
  max(case subject when'数学'then result else0end) 数学,
  max(case subject when'物理'then result else0end) 物理
from tb
groupby name
/*
姓名         语文        数学        物理          
---------- ----------- ----------- ----------- 
李四         74          84          94
张三         74          83          93
*/

--动态SQL,指subject不止语文、数学、物理这三门课程。
declare@sqlvarchar(8000)
set@sql='select Name as '+'姓名'
select@sql=@sql+' , max(case Subject when '''+ Subject +''' then Result else 0 end) ['+ Subject +']'
from (selectdistinct Subject from tb) as a
set@sql=@sql+' from tb group by name'
exec(@sql) 
/*
姓名         数学        物理        语文          
---------- ----------- ----------- ----------- 
李四         84          94          74
张三         83          93          74
*/

-------------------------------------------------------------------
/*加个平均分,总分
姓名         语文        数学        物理        平均分                总分          
---------- ----------- ----------- ----------- -------------------- ----------- 
李四         74          84          94          84.00                252
张三         74          83          93          83.33                250
*/

--静态SQL,指subject只有语文、数学、物理这三门课程。
select name 姓名,
  max(case subject when'语文'then result else0end) 语文,
  max(case subject when'数学'then result else0end) 数学,
  max(case subject when'物理'then result else0end) 物理,
  cast(avg(result*1.0) asdecimal(18,2)) 平均分,
  sum(result) 总分
from tb
groupby name
/*
姓名         语文        数学        物理        平均分                总分          
---------- ----------- ----------- ----------- -------------------- ----------- 
李四         74          84          94          84.00                252
张三         74          83          93          83.33                250
*/

--动态SQL,指subject不止语文、数学、物理这三门课程。
declare@sql1varchar(8000)
set@sql1='select Name as '+'姓名'
select@sql1=@sql1+' , max(case Subject when '''+ Subject +''' then Result else 0 end) ['+ Subject +']'
from (selectdistinct Subject from tb) as a
set@sql1=@sql1+' , cast(avg(result*1.0) as decimal(18,2)) 平均分,sum(result) 总分 from tb group by name'
exec(@sql1) 
/*
姓名         数学        物理        语文        平均分                总分          
---------- ----------- ----------- ----------- -------------------- ----------- 
李四         84          94          74          84.00                252
张三         83          93          74          83.33                250
*/

droptable tb

---------------------------------------------------------
---------------------------------------------------------
/*
如果上述两表互相换一下:即

姓名 语文 数学 物理
张三 74  83  93
李四 74  84  94

想变成 
Name       Subject Result      
---------- ------- ----------- 
李四         语文      74
李四         数学      84
李四         物理      94
张三         语文      74
张三         数学      83
张三         物理      93
*/

createtable tb1
(
   姓名 varchar(10) ,
   语文 int ,
   数学 int ,
   物理 int
)

insertinto tb1(姓名 , 语文 , 数学 , 物理) values('张三',74,83,93)
insertinto tb1(姓名 , 语文 , 数学 , 物理) values('李四',74,84,94)

select*from
(
  select 姓名 as Name , Subject ='语文' , Result = 语文 from tb1 
  unionall
  select 姓名 as Name , Subject ='数学' , Result = 数学 from tb1
  unionall
  select 姓名 as Name , Subject ='物理' , Result = 物理 from tb1
) t
orderby name , case Subject when'语文'then1when'数学'then2when'物理'then3when'总分'then4end

--------------------------------------------------------------------
/*加个平均分,总分
Name       Subject     Result               
---------- -------    -------------------- 
李四         语文      74.00
李四         数学      84.00
李四         物理      94.00
李四         平均分    84.00
李四         总分      252.00
张三         语文      74.00
张三         数学      83.00
张三         物理      93.00
张三         平均分    83.33
张三         总分      250.00
*/

select*from
(
  select 姓名 as Name , Subject ='语文' , Result = 语文 from tb1 
  unionall
  select 姓名 as Name , Subject ='数学' , Result = 数学 from tb1
  unionall
  select 姓名 as Name , Subject ='物理' , Result = 物理 from tb1
  unionall
  select 姓名 as Name , Subject ='平均分' , Result =cast((语文 + 数学 + 物理)*1.0/3asdecimal(18,2)) from tb1
  unionall
  select 姓名 as Name , Subject ='总分' , Result = 语文 + 数学 + 物理 from tb1
) t
orderby name , case Subject when'语文'then1when'数学'then2when'物理'then3when'平均分'then4when'总分'then5end

droptable tb1

信息化技术交流群:290216011 公司网址:www.scxxfw.com

SQL 查询横表变竖表的更多相关文章

  1. MySQL中横表和竖表相互转换

    一  竖表转横表 1. 首先创建竖表 create table student ( id varchar(32) primary key, name varchar (50) not null, su ...

  2. SQL竖表转横表 / 横表转竖表

    竖表转横表 竖表结构: Name Course Grade 张三 语文 75 张三 数学 80 张三 英语 90 李四 语文 95 李四 数学 55 转换后横表结构: Name 语文 数学 英语 张三 ...

  3. sql查询 所有被锁定的表

    --sql查询  所有被锁定的表 select request_session_id spid,OBJECT_NAME(resource_associated_entity_id) tableName ...

  4. SQL查询数据并插入新表

    SQL查询数据并插入新表 --如果接受数据导入的表已经存在 insert into 表 select * from tablename --如果导入数据并生成表 select * into 表 fro ...

  5. 使用SQL查询所有数据库名和表名

    使用SQL查询所有数据库名和表名 MySQL中查询所有数据库名和表名 查询所有数据库 show databases; 1 1 查询指定数据库中所有表名 select table_name from i ...

  6. SQL查询某库所有的表所有的字段及字段的属性

    then d.name else null end) 表名, a.colorder 字段序号, a.name 字段名, ( then '√'else '' end) 标识, ( then '√' el ...

  7. SQl查询数据库库名,表名、表的列名

    查询数据库 select * From master.dbo.sysdatabases where name='数据库名' and status<>512   --读取库中的所有表名 (当 ...

  8. SQL 查询两个字段相同表的不同记录

    select b.NativeName from sanleiDB.dbo.Dictionary_Native b where not EXISTS (select a.NativeName from ...

  9. sql查询当前数据库的所有表名

    SELECT sys.tables.name as TableName from sys.tables

随机推荐

  1. java的Serialization 机制

    基本使用方法               Serialization是指把类或者基本的数据类型持久化(persistence)到数据流(Stream)中,包括文件.字节流.网络数据流.         ...

  2. poj 3694 Network(双连通分量)

    题目:http://poj.org/problem?id=3694 #include <iostream> #include <cstring> #include <cs ...

  3. poj 2531 Network Saboteur( dfs )

    题目:http://poj.org/problem?id=2531 题意:一个矩阵,分成两个集合,求最大的 阻碍量 改的 一位大神的代码,比较简洁 #include<stdio.h> #i ...

  4. poj 2185 (KMP)

    完全不会啊…… 附一份题解:http://blog.sina.com.cn/s/blog_69c3f0410100tyjl.html var i,j,k,r,c,x:longint; ch:..,.. ...

  5. SQL RIGHT JOIN 关键字

    SQL RIGHT JOIN 关键字 RIGHT JOIN 关键字会右表 (table_name2) 那里返回所有的行,即使在左表 (table_name1) 中没有匹配的行. RIGHT JOIN ...

  6. 【转】armeabi和armeabi-v7a

    原文网址:http://blog.csdn.net/dxpqxb/article/details/7721156 在我们android APK的根目录有一个 libs文件夹,此文件夹下包含了armea ...

  7. SQL Server使用规范(转)

    常见的字段类型选择 1.字符类型建议采用varchar/nvarchar数据类型 2.金额货币建议采用money数据类型 3.科学计数建议采用numeric数据类型 4.自增长标识建议采用bigint ...

  8. tomcat server.xml配置详解

    由于 Tomcat 基于 Java,实际上在各种 Linux 发行版里的配置方法都大同小异,只是我看见在 Arch Linux 环境里搭建 Tomcat 的文章比较少,所以在 Arch Linux 实 ...

  9. We need the sql script to query the table Ditronics.Kiosk.Journal to find journal with mismatch denom information versus amount.

    CREATE TABLE #MoneyTable ( Id , ) PRIMARY KEY , MoneyName ) , Cents INT ) INSERT INTO #MoneyTable ( ...

  10. SQL Server: Difference Between Locking, Blocking and Dead Locking

    Like ever, today’s article of Pinal Dave was interesting and informative. After, our mutual discussi ...