简体   繁体   中英

Select multiple column values in single query - oracle

I have two tables that store email information:

  • EMAIL
  • EMAIL_ADDRESS

EMAIL has:

  • email ID
  • timestamp
  • and other info we don't care about

EMAIL_ADDRESS has:

  • ID (foreign key references EMAIL.ID)
  • EMAIL_ADDRESS
  • TYPE (to, from)

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

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')

尝试使用GROUP BY e.IDGROUP BY ea.id

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  |d@gmail.com| to   |
| 1  |c@gmail.com| from |
| 2  |i@gmail.com| to   |
| 2  |k@gmail.com| 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    |d@gmail.com|c@gmail.com|2014-02-14 17:30:32.803|
|   2    |i@gmail.com|k@gmail.com|2014-02-24 17:30:32.803|        

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