首页  >  文章  >  数据库  >  数据库行列互换

数据库行列互换

WBOY
WBOY原创
2016-06-07 15:36:141519浏览

1:SQL Server : case group 2:oracle decode group 假设用到的sql语句为: SELECT [姓名],[时代],[金钱] FROM [test].[dbo].[people] 想要等到如下的结果: 姓名 年轻 中年 老年 张三 1000 5000 800 李四 1200 6000 500 SQL Server: case [时代] when '年轻'

1:SQL Server : case group

 2:oracle decode group

假设用到的sql语句为:

SELECT [姓名],[时代],[金钱]
  FROM [test].[dbo].[people] 

数据库行列互换想要等到如下的结果:

姓名 年轻 中年 老年
张三 1000 5000 800
李四 1200 6000 500

SQL Server:

  case  [时代] when '年轻' then [金钱] else 0 end as 年轻

  或

  case when  [时代]= '年轻' then [金钱] else 0 end as 年轻

select [姓名],sum([年轻]) as 年轻,sum([中年]) as 中年,sum([老年]) as 老年 from
(SELECT [姓名],[时代],[金钱], 

case  [时代] when '年轻' then [金钱] else 0 end as 年轻,
case  [时代] when '中年' then [金钱] else 0 end as 中年,
case  [时代] when '老年' then [金钱] else 0 end as 老年 

  FROM [test].[dbo].[people]) t
  group by [姓名]

 

Oracle :  decode(时代,'年轻',金钱,0)) 年轻

select [姓名], max(decode([时代],年轻,金钱,0))as 年轻, max(decode([时代],中年,金钱,0))as 中年, max(decode([时代],老年,金钱,0))as 老年 from [test].[dbo].[people] group by 姓名.

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn