根据另一列值 - ORACLE将列分为两列

时间:2013-11-12 12:33:59

标签: sql oracle

首先,希望标题表达问题。否则,欢迎任何建议。我的问题是我有以下表结构:

+----+------+------------------+-------------+
| ID | Name | recipient_sender |  user       |
+----+------+------------------+-------------+
|  1 | A    |                1 | X           |
|  2 | B    |                2 | Y           |
|  3 | A    |                2 | Z           |
|  4 | B    |                1 | U           |
|    |      |                  |             |
+----+------+------------------+-------------+

recipient_sender列中,值1表示用户是收件人,值2表示用户是发件人。
我需要以下列方式呈现数据:

+----+------+-----------+---------+
| ID | Name | recipient |  sender |
+----+------+-----------+---------+
|  1 | A    | X         | Z       |
|  2 | B    | U         | Y       |
+----+------+-----------+---------+

我尝试过自我加入但是没有用。我无法将MAXCASE WHEN一起使用,因为记录数量太大。

注意:请忽略坏表设计,因为它只是真实表格的简化示例

4 个答案:

答案 0 :(得分:1)

也许你可以试试这个:

  select min(id) id, 
         name,
         max(decode(recipient_sender, 1, user, '')) sender,
         max(decode(recipient_sender, 2, user, '')) recipient
    from t
group by name

您可以查看演示here on SQLFiddle

答案 1 :(得分:1)

请尝试:

SELECT
  MIN(ID) ID
  Name, 
  max(case when recipient_sender=1 then user else null end) sender, 
  max(case when recipient_sender=2 then user else null end) recipient
From yourTable 
group by Name

答案 2 :(得分:0)

创建新表(具有更好的结构):

insert into <newtable> as 
select distinct 
    id, 
    name, 
    user as recipient, 
    (select user from <tablename> where id = recip.id and name = recip.name) as sender
from <tablename> recip
抱歉,这里没有神谕。

答案 3 :(得分:0)

您可以使用此查询选择值

SELECT t.id,
       t.name,
       case
         when t.recipient_sender = 1 then
          t.user
         ELSE
          t2.user
       END as recipient,
       case
         when t.recipient_sender = 2 then
          t.user
         ELSE
          t2.user
       END as sender
  FROM your_table t
  JOIN your_table t2
    ON t.name = t2.name
   AND t.id != t2.id

在此查询之后,您可以添加DISTINCT关键字或GROUP它们......

此查询用于连接具有NAME列的表,但如果您有一些消息标识,请使用该标识连接表,