SQL行列互换

行列交换

题目1:数据库中有一张如下所示的表,表名为sales。

季度销售量
1991 1 11
1991 2 12
1991 3 13
1991 4 14
1992 1 21
1992 2 22
1992 3 23
1992 4 24


要求:写一个SQL语句查询出如下所示的结果。

一季度 二季度 三季度 四季度
1991 11 12 13 14
1992 21 22 23 24


运用 SQL
条件控制(case when...then...else...end

select 年, sum(case when 季度=1 then 销售量 else 0 end) as 一季度,
              sum(case when 季度=2 then 销售量 else 0 end) as 二季度,      
              sum(case when 季度=3 then 销售量 else 0 end) as 三季度,
              sum(case when 季度=4 then 销售量 else 0 end) as 四季度
from sales 
group by 年;

case when...then...else...end语句的逻辑为:

case when 条件 then value_a else value_b end该语句表示:当条件成立时,值为value_a,不成立时值取value_b

值交换

题目2:工资表中包含性别一列,m 代表男性,f 代表女性。 

交换所有f和m值(即,将所有f值更改为m,反之亦然),只需一条更新语句,而无需中间临时表。 请注意,必须编写一条更新语句,请勿针对此问题编写任何查询语句

 sql语句:

UPDATE salary
SET sex = (CASE WHEN sex = 'm' THEN 'f' ELSE 'm' END);

结果

 

 

 

posted @ 2015-04-20 17:29  peterYong  阅读(651)  评论(0编辑  收藏  举报