I am trying to formulate a query in PostgresSQL, my table looks like this:
Master_Account | Sub_Account | Cost |
---|---|---|
123 | 777 | 15 |
123 | 888 | 10 |
123 | 999 | 20 |
456 | 111 | 10 |
456 | 222 | -15 |
789 | 789 | 10 |
I am trying to select rows where the master account and sub accounts are different values (there are cases where they are the same, like the last row), and where cost is both positive and negative under the master account. So my desired output would be only these rows:
Master_Account | Sub_Account | Cost |
---|---|---|
456 | 111 | 10 |
456 | 222 | -15 |
I am essentially trying to select rows where Master Account and Sub Account are different, and where cost contains both positive and negative values, not both positive or both negative.
I was thinking something like:
select * from table where master_account != sub_account and where exists (cost > 0 and cost < 0)
2
Answers
There are more succinct ways to write this, but this is a way that doesn’t use window functions.
Rationale – Simple where clause to get the records with different master and sub account numbers. Then an exists to find the ones which have at least one different sign for the master number.
Edited for the additional stipulation in the comment. There’s a couple ways to interpret that new request. If it’d satisfy that it must be a different sub_account with a different sign, then simply
works. If for the same sub_account it’d satisfy if there was a different sign, and a different sub_account with an arbitrary sign you’d do it like this:
Edit:
And just to show a common trick using window functions. min() over () <> max() over () is handy when you are looking for distinct values over a grouping.
Could you please try