ghost_1989
ghost_1989

Reputation: 158

Select multiple column values in single query - oracle

I have two tables that store email information:

EMAIL has:

EMAIL_ADDRESS has:

Say I have 6 rows in EMAIL - the query should return the ID, timestamp, to and from address.

At the moment I have this:

SELECT ea.EMAIL_ADDRESS, e.ID, e.sent_date
FROM EMAIL_ADDRESS ea, CHANN_EMAIL e
WHERE e.ID=ea.id
AND ea.TYPE in ('to','from')

This returns 12 rows, in the format: -to, ID, date -from, ID, date

What would the query be so I would have 6 rows with: -to, from, ID, date

Upvotes: 0

Views: 11922

Answers (3)

Dipendu Paul
Dipendu Paul

Reputation: 2753

Sample Data: email table:

| email_id |     timestamp          |
-------------------------------
| 1        | 2014-02-14 17:30:32.803|
| 2        | 2014-02-24 17:30:32.803|

email_address table:

| id | email_add | type |
-------------------------
| 1  |[email protected]| to   |
| 1  |[email protected]| from |
| 2  |[email protected]| to   |
| 2  |[email protected]| from |

Query:

SELECT tab.email_id, MAX([to]) AS [to], MAX([from]) AS [from], MAX(tab.timestamp) AS [time] FROM
(SELECT e.email_id, 
CASE WHEN type= 'to' THEN ea.email_add ELSE NULL END AS [to],
CASE WHEN type= 'from' THEN ea.email_add ELSE NULL END AS [from], e.timestamp
FROM email e
INNER JOIN email_address ea
ON e.email_id = ea.id) tab
GROUP BY tab.email_id

Result:

|email_id|    to     |  from     |   time                |
----------------------------------------------------------
|   1    |[email protected]|[email protected]|2014-02-14 17:30:32.803|
|   2    |[email protected]|[email protected]|2014-02-24 17:30:32.803|        

Upvotes: 0

Reza ArabQaeni
Reza ArabQaeni

Reputation: 4907

You must distinct EMAIL_ADDRESS table to two view:

SELECT eat.EMAIL_ADDRESS as to ,ea.EMAIL_ADDRESS as from, e.ID, e.sent_date
FROM EMAIL_ADDRESS ea, CHANN_EMAIL e,EMAIL_ADDRESS eat
WHERE e.ID=ea.id and e.ID=eat.id
AND ea.TYPE in ('from') AND eat.TYPE in ('to')

Upvotes: 1

pulsar
pulsar

Reputation: 987

try using GROUP BY e.ID or GROUP BY ea.id

Upvotes: 0

Related Questions