【问题标题】:SQL join and add row values as column namesSQL 连接并添加行值作为列名
【发布时间】:2022-09-24 00:13:28
【问题描述】:

我需要你的帮助。

给定3张桌子

表名1:Table1

ID Name
1 Mike
2 John

表名 2:join1

ID column value
1 job_description manager
1 salary 3000

表名 3:join2

ID column value
1 Hobby cycling
1 Date of join 12.01.2020

输出应该加入 ID=1 的 Table1 并加入两个表 Join1 和 Join2 ,其中行作为来自 join1 的列名 \"job_description\",并且有 2 行作为来自 join2 表的列 \"Hobby\" 和 \"salary\",如下所示:

ID name job_description Hobby salary
1 Mike manager cycling 3000

谢谢

    标签: sql oracle


    【解决方案1】:

    您可以根据您的标准加入所有三个表。例如:

    select a.id, a.name, b.value, c.value
    from table1 a
    join join1 b on b.id = a.id and b.column = 'job_description'
    join join2 c on c.id = a.id and c.column = 'Hobby'
    where a.id = 1
    

    附带说明一下,表名(join1join2)作为实体名称可能会有些混乱。列名(columnvalue)可能过于通用,但这取决于您的数据库设计。

    编辑

    对于更新后的问题,您希望为主表中的同一行检索辅助表的多个行值。典型的解决方案是使用聚合或子查询。使用后者,查询可以采用以下形式:

    select a.id, a.name, 
      (select value from join1 b where b.id = a.id
         and b.column = 'job_description') as job_description,
      c.value as hobby,
      (select value from join1 b where b.id = a.id
         and b.column = 'salary') as salary
    from table1 a
    join join2 c on c.id = a.id and c.column = 'Hobby'
    where a.id = 1
    

    【讨论】:

    • 谢谢,但是我忘记在输出中添加 1 列,如果我需要从第三个表(join2)到输出的多于 1 行,如何解决?
    • 非常感谢您
    【解决方案2】:
    select  id
           ,t.name
           ,"'job_description'" as job_description
           ,t3."value"          as Hobby
           ,"'salary'"          as Salary
    from    t2
    pivot   (max("value") for "column" in('job_description',  'salary')) p join t using(id) join t3 using(id) 
    where   "column" = 'Hobby'
    
    ID NAME JOB_DESCRIPTION HOBBY SALARY
    1 Mike manager cycling 3000

    Fiddle

    【讨论】:

    • 查看更新的答案
    猜你喜欢
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    相关资源
    最近更新 更多