Reputation: 158
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
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
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