I am looking to return the following information for each contact contained within a set of tables:
Contact_id | first_Event_date | first_Event_id | event_type
id123456 | 01/12/2007 | eveid123456 | table1
id456455 | 05/06/1999 | eveid456585 | table4
Where the data reflects the first event that each contact has ever been involved with (which could be contained in any of up to 8 tables), and the event_type tells you from which table the event is from.
I have the following query script as a starting point, and it works fine when trying to pull just the contact_id and event_date but when I try to also include the event_id it seems to arbitrarily pull an ID from somewhere which is not correct:
SELECT
table1.contact_id AS contact_id
MIN(table1.date_received) AS event_date
table1.event_id AS event_id
FROM table1
GROUP BY table1.contact_id
UNION
SELECT
table2.contact_id
MIN(table2.date_received)
table2.event_id
FROM table2
GROUP BY table2.contact_id
And this is repeated for tables 3-6. I know that I need to also include the table1.event_id etc in the GROUP BY clause, but when I do it returns all mentions of each event for each contact (for each table), so one contact has multiple rows returned for the table1 subquery when there should be at most 1 row returned.
Additionally, in case in helps not all contacts will appear in all of the tables (but will appear at least once across all of the table) and I'm using sql server 2005.
Thanks in advance :)