【问题标题】:How to get 2 values of same num to 2 separate columns如何将 2 个相同数字的值分配给 2 个单独的列
【发布时间】:2020-03-23 12:48:20
【问题描述】:

我有这样的表:

num |type|value
--------------
1 | a   | 5
1 | b   | 7
3 | c   | 9
2 | a   | 6
2 | b   | 9

想要这样的结果:

num| value (a) | value (b)
-------------------------
1  |    5      |   7
2  |    6      |   9

【问题讨论】:

  • 好的。你的问题是什么?
  • 3 怎么了?
  • 它是 Oracle 数据库
  • "3" - 我不希望它出现在报告中

标签: sql oracle select


【解决方案1】:

您可以使用自联接,这也将删除只有一个值的行(示例数据中的 num = 3)

select t1.num, t1.value as value_a, t2.value as value_b
from the_table t1 
  join the_table t2 on t1.num = t2.num and t2.type = 'b'
where t1.type = 'a'

【讨论】:

  • 您好,我还有一个问题。如果没有第 2 行怎么办。在那种情况下,我得到空结果。这种情况如何处理?
  • @BartekK:你可能想要一个左连接
【解决方案2】:

您可以使用 GROUP BY 和 CASE,如:

select
  num,
  max(case when type = 'a' then value end) as value_a,
  max(case when type = 'b' then value end) as value_b
from t
group by num

【讨论】:

    【解决方案3】:

    我会自己加入表格,一次用于 a,一次用于 b

    SELECT a.num, a.value, b.value
    FROM   mytable a
    JOIN   mytable b ON a.num = b.num AND a.type = 'a' AND b.type = 'b'
    

    【讨论】:

      猜你喜欢
      • 2023-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      相关资源
      最近更新 更多