Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

UNION with Group By

Status
Not open for further replies.

JMay0816

Programmer
Mar 1, 2007
34
0
0
US
I am selecting records from two tables:

select a.fileid, a.outby, a.adddate, b.email from table1 a, table2 b where a.outby=b.uid and a.adddate < date_add(now(), interval -6 day) and a.status in (1,2) UNION
select a.fileid, a.outby, a.adddate, b.email from table3 a, table2 b where a.outby=b.uid and a.adddate < date_add(now(), interval -6 day) and a.status in (1,2)

This returns 4 records:
+---------+--------+------------+-------------------+
| fileid | outby | adddate | email |
+---------+--------+------------+-------------------+
| 0001013 | user01 | 2007-03-31 | User.01@email.com |
| 0001014 | user02 | 2004-02-02 | User.02@email.com |
| 0000096 | user01 | 2006-12-04 | User.01@email.com |
| 0000097 | user01 | 2007-03-30 | User.01@email.com |
+---------+--------+------------+-------------------+

I am trying to group this result set by email. Thus my output should only be:

User.01@email.com
User.02@email.com

Can't seem to hit on the right combination. Can someone assist?

thx
 
Hi

Code:
select a.fileid, a.outby, a.adddate, b.email from table1 a, table2 b where a.outby=b.uid and a.adddate <  date_add(now(), interval -6 day) and a.status in (1,2)  UNION
select a.fileid, a.outby, a.adddate, b.email from table3 a, table2 b where a.outby=b.uid and a.adddate <  date_add(now(), interval -6 day) and a.status in (1,2) [red]order by email[/red]

Feherke.
 
that still returns four records instead of the desired two.
 
Finally got it:

select distinct email from (
select a.fileid, a.outby, a.adddate, b.email from table1 a, table2 b where a.outby=b.uid and a.adddate < date_add(now(), interval -6 day) and a.status in (1,2) UNION
select a.fileid, a.outby, a.adddate, b.email from table3 a, table2 b where a.outby=b.uid and a.adddate < date_add(now(), interval -6 day) and a.status in (1,2) order by email
) as newmail
 
Finally got it:

select distinct email from (
(select a.fileid, a.outby, a.adddate, b.email from table1 a, table2 b where a.outby=b.uid and a.adddate < date_add(now(), interval -6 day) and a.status in (1,2)) UNION
(select a.fileid, a.outby, a.adddate, b.email from table3 a, table2 b where a.outby=b.uid and a.adddate < date_add(now(), interval -6 day) and a.status in (1,2))
) as newmail
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top