Reputation: 5170
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
Upvotes: 0
Views: 2414
Reputation: 18659
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
Upvotes: 1
Reputation: 2060
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.
Upvotes: 0
Reputation: 7119
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.
Upvotes: 1
Reputation: 3690
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 ,
Upvotes: 0