您的位置:首页 > 数据库

sql语句行列转换

2011-11-25 17:04 162 查看
假设有表emp_phone如下:
NAME TYPE PHONE
张三 1 1234-5678
张三 2 4567-7890
张三 3 6000-1001
李四 1 2123-1237
李四 3 6001-5600
马五u 1 3248-1378
马五 2 3423-3948
王二(没麻子) 2 2890-1245
。。。

表里放着张三李四王二麻子等等主人翁的电话号码。(TYPE 1/2/3分别对应家/办公室/手机)。如果要把每个人的所有电话放在一行上,就是行转列了。结果如下:
NAME HOME OFFICE MOBILE
张三 1234-5678 4567-7890 6000-1001
李四 2123-1237 6001-5600
马五 3248-1378 3423-3948
王二(没麻子) 2890-1245

写这个SQL的技巧就是按姓名分组,然后使每一组每一类的电话号码最多只有一个,里边用到的分组函数都是聋子的耳朵-摆设。用MAX可以,MIN也行。

max作用是避免做笛卡尔积。

那位看官说了:“能不能再变回去?”能,不能戏法不就漏了不是?
这儿要用到另一的技巧就是笛卡尔乘积,将一行复制成三行,每一行取一个类型的电话
偷个懒儿把上边的结果表叫emp_phone_x,把列还原成行的SQL:

SELECT
NAME,
DECODE (lvl, 1, home, 2, office, 3, mobile) phone
FROM
emp_phone_x,
(SELECT LEVEL lvl
FROM DUAL
CONNECT BY LEVEL <= 3)
WHERE
DECODE (lvl, 1, home, 2, office, 3, mobile) IS NOT NULL /

再如:

select every_day "日期",max(decode(position,0,touch_count,0)) "头上",
max(decode(position,1,touch_count,0)) "头下",
max(decode(position,2,touch_count,0)) "后脑",
max(decode(position,3,touch_count,0)) "胸",
max(decode(position,4,touch_count,0)) "后背",
max(decode(position,5,touch_count,0)) "肚子",
max(decode(position,6,touch_count,0)) "裙子前",
max(decode(position,7,touch_count,0)) "裙子后",
max(decode(position,8,touch_count,0)) "右上臂",
max(decode(position,9,touch_count,0)) "左上臂",
max(decode(position,10,touch_count,0)) "右手",
max(decode(position,11,touch_count,0)) "左手",
max(decode(position,12,touch_count,0)) "右大腿",
max(decode(position,13,touch_count,0)) "左大腿",
max(decode(position,14,touch_count,0)) "右小腿",
max(decode(position,15,touch_count,0)) "左小腿",
max(decode(position,16,touch_count,0)) "右后腿",
max(decode(position,17,touch_count,0)) "左后腿"
from iloli_touch where every_day>date'2011-11-1' group by every_day order by every_day desc
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: