Question

Below is the query that I created, but upon validation of the results produced, the query is producing inaccurate results.

select a.acct_id, c.bill_dt
from account a inner join invoice_detail b  on a.acct_id = b.acct_id 
inner join 
    (select acct_id, max(bill_dt) as bill_dt from invoice_detail  
    where bill_dt < '1/1/2014'
    group by acct_id)c on b.acct_id = c.acct_id
and a.acct_stat_id = '275'
and not a.acct_id in (select acct_id from contract where cntrct_stat_id in ('394','554','555','556'))
and not a.acct_id in (select acct_id from billing_adj where bill_adj_stat_id in ('4','394','553','554','555'))
group by a.acct_id, c.bill_dt
order by a.acct_id ASC

I would like my results to only show acct_ids and the max(bill_dt) after meeting all query criteria. The invoice_detail table contains multiple records for an acct_id. However, when I executed the query, I randomly selected an acct_id that had a max(bill_dt) of 12/31/2013 for validation. I looked in the invoice_detail table by acct_id and the results came back with additional records with a bill_dt greater than 1/1/2014. I want to identify acct_ids that do not have any invoices after 1/1/2014.

Was it helpful?

Solution

I want to identify acct_ids that do not have any invoices after 1/1/2014

Then your condition in your subquery needs to be:

HAVING max(bill_dt) < '1/1/2014'

You're also not using the invoice_detail table except in the subquery, so you can take it out of the main query:

select a.acct_id, c.bill_dt
from account a 
inner join 
    ( select acct_id, max(bill_dt) as bill_dt from invoice_detail  
      group by acct_id
      HAVING max(bill_dt) < '1/1/2014'
    ) c on a.acct_id = c.acct_id
and a.acct_stat_id = '275'
and not a.acct_id in (select acct_id from contract where cntrct_stat_id in ('394','554','555','556'))
and not a.acct_id in (select acct_id from billing_adj where bill_adj_stat_id in ('4','394','553','554','555'))
group by a.acct_id, c.bill_dt
order by a.acct_id ASC
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top