简体   繁体   中英

divide a column into two based on another column value - ORACLE

First, hope the title expresses the issue. Otherwise, any suggest is welcomed. My issue is I have the following table structure:

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

Whereby in the column recipient_sender the value 1 means the user is recipient, the value 2 means the user is sender.
I need to present data in the following way:

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

I've tried self-join but it did not work. I cannot use MAX with CASE WHEN , as the number of records is too big.

Note: Please ignore the bad table design as it's just a simplified example of the real one

maybe you can try this:

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

You can check a demo here on SQLFiddle .

Please try:

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

Create new Table (with better struct):

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

sorry, have no oracle here.

You can select values with this query

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

after this query you can add DISTINCT keyword or GROUP them ...

this query is used to join tables with column NAME but if you have some identity for message , join tables using that ,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM