SQL语句-在一个列中获取多个值

时间:2019-07-18 06:45:13

标签: sql database oracle

我有一个表,其中包含以下数据:

  id | name | value

    12 | KREA | 3,7 

    13 | KREA | 12.6

    12 | GFR  | 2.2

    13 | GFR  | 1.7

现在我想在这样的一列中获取krea和gfr的名称和值:

 id | name1 | value1 | name2 | value2

    12 | KREA  | 3.7    | GFR   | 2.2

...

我尝试加入,但没有成功。

select rps1.id, rps1.name, rps1.value, rps2.id, rps2.name, rps2.value 
  from table1 rps1, table1 rps2 
 where rps1.name like 'KREA' 
    or rps2.name like 'GRFR' and rps1.id = rps2.id
   and crd > '17.07.2019 00:00:00' order by id

谁能告诉我我做错了什么?提前致谢! :)

2 个答案:

答案 0 :(得分:2)

使用它。

select
  t1.id,
  t1.name,
  t1.value,
  t2.id,
  t2.name,
  t2.value
from
  (select id, name, value from table1 where name='KREA' and crd > '17.07.2019 00:00:00') t1
join
  (select id, name, value from table1 where name='GFR' and crd > '17.07.2019 00:00:00') t2
        on t1.id = t2.id
order by
  t1.id

答案 1 :(得分:0)

您尝试过的查询非常好,除了一些错误。

rps1.name like 'KREA' 
    or rps2.name like 'GRFR' 
--> need to use AND instead of OR
--> need to use 'GFR' instead of 'GRFR' 

order by id
--> Need to use alias rps1.id

-因此您的查询将如下所示:

select rps1.id, rps1.name, rps1.value, rps2.id, rps2.name, rps2.value 
  from table1 rps1, table1 rps2 
 where rps1.name like 'KREA' 
    AND rps2.name like 'GFR' and rps1.id = rps2.id
   and crd > '17.07.2019 00:00:00' 
   order by rps1.id

db<>fiddle demo

干杯!