Rumah  >  Artikel  >  pangkalan data  >  数据库行列互换

数据库行列互换

WBOY
WBOYasal
2016-06-07 15:36:141520semak imbas

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 姓名.

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:mongo数据库的操作Artikel seterusnya:重构的10个小技巧