oracle sql加入同一个表中的2行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6614867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 00:07:30 来源:igfitidea点击:
sql join 2 rows in the same table
提问by Dejell
I have the following table:
我有下表:
Name Type Value
---------------------
mike phone 123
mike address nyc
bob address nj
bob phone 333
I want to have the result like this:
我想要这样的结果:
name value value
-------------------
mike nyc 123
bob nj 333
How can I do it?
我该怎么做?
回答by cdonner
it is called a self-join. the trick is to use aliases.
它被称为自连接。诀窍是使用别名。
select
address.name,
address.value as address,
phone.value as phone
from
yourtable as address left join
yourtable as phone on address.name = phone.name
where address.type = 'address' and
(phone.type is null or phone.type = 'phone')
The query assumes that each name has an address, but phone numbers are optional.
该查询假设每个名字都有一个地址,但电话号码是可选的。
回答by Kerrek SB
Something like this:
像这样的东西:
SELECT a.name AS name, phone, address
FROM (SELECT name, value AS phone FROM mytable WHERE type = "phone") AS a
JOIN (SELECT name, value AS address FROM mytable WHERE type = "address") AS b
ON(a.name = b.name);