行列转换

╰+哭是因爲堅強的太久メ 2022-04-22 14:28 323阅读 0赞

表一:

group c1 c2 c3 c4
-———————————————————————-
1 11 12 13 14
2 21 22 23 24
3 31 32 33 34

表二:

group c
-—————————————
1 11
1 12
1 13
1 14
2 21
2 22
2 23
2 24
3 31
3 32
3 33
3 34

由表一转到表二,是列转行
有表二转到表一,是行转列

行转列

  1. with temp as
  2. (
  3. select 1 group_1,11 c1,12 c2,13 c3,14 c4 from dual union
  4. select 2,21,22,23,24 from dual union
  5. select 3,31,32,33,34 from dual
  6. )
  7. select group_1,
  8. regexp_substr(c,'[^,]+',1,n) c
  9. from
  10. (select group_1,c1||','||c2||','||c3||','||c4 c from temp),
  11. (select rownum n from dual connect by rownum<=4)
  12. where n<=length(regexp_replace(c,'[^,]',null)) + 1
  13. order by group_1,c
  14. 列转行
  15. 方法一:
  16. with temp as
  17. (
  18. select '张三' f1,'语文' f2,60 f3 from dual union select '张三' f1,'数学' f2,63 f3 from dual union select '张三' f1,'物理' f2,66 f3 from dual union select '张三' f1,'化学' f2,69 f3 from dual union
  19. select '李四' f1,'语文' f2,61 f3 from dual union select '李四' f1,'数学' f2,64 f3 from dual union select '李四' f1,'物理' f2,67 f3 from dual union select '李四' f1,'化学' f2,70 f3 from dual union
  20. select '王五' f1,'语文' f2,62 f3 from dual union select '王五' f1,'数学' f2,65 f3 from dual union select '王五' f1,'物理' f2,68 f3 from dual union select '王五' f1,'化学' f2,71 f3 from dual
  21. )
  22. select f1 XM,
  23. (select f3 from temp where f1 = t.f1 and f2='语文') 语文,
  24. (select f3 from temp where f1 = t.f1 and f2='数学') 数学,
  25. (select f3 from temp where f1 = t.f1 and f2='物理') 物理,
  26. (select f3 from temp where f1 = t.f1 and f2='化学') 化学
  27. from temp t group by f1
  28. 方法二:
  29. with temp as
  30. (
  31. select '张三' f1,'语文' f2,60 f3 from dual union select '张三' f1,'数学' f2,63 f3 from dual union select '张三' f1,'物理' f2,66 f3 from dual union select '张三' f1,'化学' f2,69 f3 from dual union
  32. select '李四' f1,'语文' f2,61 f3 from dual union select '李四' f1,'数学' f2,64 f3 from dual union select '李四' f1,'物理' f2,67 f3 from dual union select '李四' f1,'化学' f2,70 f3 from dual union
  33. select '王五' f1,'语文' f2,62 f3 from dual union select '王五' f1,'数学' f2,65 f3 from dual union select '王五' f1,'物理' f2,68 f3 from dual union select '王五' f1,'化学' f2,71 f3 from dual
  34. )
  35. select f1,
  36. sum(decode(f2,'语文', f3,null)) "语文",
  37. sum(decode(f2,'数学', f3,null)) "数学",
  38. sum(decode(f2,'物理', f3,null)) "物理",
  39. sum(decode(f2,'化学', f3,null)) "化学"
  40. from temp group by f1

发表评论

表情:
评论列表 (有 0 条评论,323人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Oracle行列转换

    11g之后,oracle增加了pivot和unpivot语句,可以很方便的完成这个转换。 没有安装,则没有测试在本文中写出,网上看到一篇很好的文章,地址:https://b