I need to combine two result sets and I feel I am so close but just don't see how to wrap this all up:
Here's one query with a small result set, (give me inactives)
SELECT MAX(set_date) AS most_recent_inactive, key_value, statusid
FROM status_history
WHERE base_table = 'userinfo'
AND statusid = 10 AND set_date > TO_DATE('2012-10-01', 'YYYY-MM-DD')
GROUP BY key_value, statusid
Output:
recent_inactive key_value statusid
2013-01-30 15 10
2013-06-04 261 10
2013-06-18 352 10
2012-10-04 383 10
2013-01-22 488 10
2013-03-04 711 10
2013-06-19 749 10
2013-03-05 806 10
Another query with a small result set (give me actives)
SELECT MAX (set_date) AS most_recent_active, key_value, statusid
FROM status_history
WHERE base_table = 'userinfo'
AND statusid =11
GROUP BY key_value, statusid
Output:
recent_active key_value statusid
2002-01-01 3 11
2002-01-01 5 11
2002-01-01 14 11
2002-01-01 15 11
2002-01-01 21 11
2002-01-01 23 11
2002-01-01 25 11
2002-01-01 26 11
I want to get all of the actives and inactives together, so I union them all
SELECT NULL AS most_recent_active, MAX(set_date) AS most_recent_inactive, key_value, statusid
FROM status_history
WHERE base_table = 'userinfo'
AND statusid = 10 AND set_date > TO_DATE('2012-10-01', 'YYYY-MM-DD')
GROUP BY key_value, statusid
UNION all
SELECT MAX(set_date) AS most_recent_active, NULL AS most_recent_inactive, key_value, statusid
FROM status_history
WHERE base_table = 'userinfo'
AND statusid = 11
GROUP BY key_value, statusid
ORDER by key_value
Output:
recent_active recent_inactive key_value statusid
2002-01-01 null 3 11
2002-01-01 null 5 11
2002-01-01 null 14 11
null 2013-01-30 15 10
2002-01-01 null 15 11
2002-01-01 null 21 11
2002-01-01 null 23 11
2002-01-01 null 25 11
2002-01-01 null 26 11
2002-01-01 null 27 11
2002-01-01 null 29 1
The problem is key_value 15 is duplicated.
The values are correct, but i want that record and all subsequent duplicates "flattened," row 15 and all other matches coming through as one record with both date fields set.
Again, I feel I'm so close but how do I wrap this all up?
Thank you?