SQL - Return all records for an account based on comparison between records for that account

StackOverflow https://stackoverflow.com/questions/22788019

  •  25-06-2023
  •  | 
  •  

Question

SQL novice here. So, i would like to return records from a table for an account where at least one of those records meets a certain criteria.

We've got a program that should allocate cash to old invoices before new ones. It isn't and i need to find records that have been affected.

I want to return all records for an account if there is;
an open amount > 0 for a record that is older than a record for the same account where the Open Amount is zero or less than the gross amount.


So in the below example, Account A1 has allocated correctly. I want my query to return all the records for accounts B2 and C3.


I think i need to use some combination of HAVING and possibly a subquery but its got me confused! Any help is greatly appreciated! Thank you.

UKID     ACCOUNT    DATE        OPEN_AMOUNT    GROSS_AMOUNT
1        A1         12/03/14    100            100  
2        A1         12/02/14    0              150
3        B2         21/03/14    0              100  
4        B2         21/02/14    100            100
5        C3         01/03/14    50             100
6        C3         01/02/14    50             100
Was it helpful?

Solution 2

Something like

select *
from   mytable
where  account in (select ext.account
                   from   mytable ext
                   inner join (SELECT account, date 
                              FROM mytable ext 
                              WHERE OPEN_AMOUNT = 0 
                                 or OPEN_AMOUNT < gross_amount) sub
                              on ext.account = sub.account 
                             and ext.date < sub.date
                   where  open_amount > 0)

should do.

If you need something more like a chain control it'll be more difficoult.

Can you please specify the database you are using? Some db specific feature can actually help a lot.

OTHER TIPS

You should be able to do this:

SELECT * 
FROM YourTable
WHERE ACCOUNT IN (
                    SELECT DISTINCT ACCOUNT
                    FROM YourTable
                    WHERE OPEN_AMOUNT <> 0
                 )

You need that second query to determine all accounts that have a non zero open amount. Then with that list you can get all of the records associated with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top