I have two tables,
accounts
= accounts in my app (id
,name
,created_at
)accounts_history
= account change history (history_id
,account_id
,history_change_date
,field
,status_name
)
In the accounts_history
table there is a column that categorizes the change to an account record (field
) that can contain two values, field=Status
(value changed on record) or field=Created
(Account record was created). Every accounts
record should have a record in accounts_history
for field=Created
, but does not always have a record for field=Status
.
What I am trying to query is a count of the accounts and their field=Status
changes and if one does not exist for an accounts
record, then default to storing the field=Created
record and COALESCE
the column status_name
(Associated with field=Status
) with the value New
.
With my current query I retrieve a table of accounts with each associated Status
and Created
record, but not de-duplicated by the field
conditional.
Should I be using a UNION
or sub-query?
Current Query:
SELECT accounts.id as id
, accounts.created_at
, accounts_history.history_id as accounts_history_id
, accounts_history.accounts_id
, accounts_history.history_change_date
, accounts_history.field
, accounts_history.status_name
FROM accounts
LEFT JOIN accounts_history
ON accounts_history.accounts_id = accounts.id
WHERE accounts.created_at::date = date '2018-03-14' AND (accounts_history.field = 'Status' OR accounts_history.field = 'created')
LIMIT 10;