Skip to Main Content
  • Questions
  • How to select a record having both negative and positive values for same id?

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Muhammad.

Asked: February 08, 2018 - 3:40 pm UTC

Last updated: February 09, 2018 - 10:49 am UTC

Version: 11g

Viewed 1000+ times

You Asked

I have the following records in a table

REC_ID START_DATE MEM_ID PRODUCT CODE PAID_AMOUNT
1001 20170204 2547 DAIRY 2233 52
1001 20170204 2547 DAIRY 2233 -52

So how could I write a query to display the above data? There are more records in a table where rec_id, start_date, mem_id, product, code is same but paid amount is different but both paid_amount has positive values. I am only interested where rec_id, start_date, mem_id, product, code is same but first paid_amount is > 0 and second paid_amount < 0.

I try different ways to achieve that but its not working.

and Chris said...

Here's one way to do it:

- Group by the columns that you want to check for duplicates
- Return those having a min value < 0 and max value > 0

e.g.:

with rws as (
  select 1 id, 'POSONLY' dsc, 1 val from dual union all
  select 1 id, 'POSONLY' dsc, 2 val from dual union all
  select 2 id, 'POSNEG' dsc, -1 val from dual union all
  select 2 id, 'POSNEG' dsc, 1 val from dual union all
  select 3 id, 'NEGONLY' dsc, -1 val from dual union all
  select 3 id, 'NEGONLY' dsc, -1 val from dual
)
  select id, dsc, min(val), max(val)
  from   rws
  group  by id, dsc
  having min(val) < 0 and max(val)> 0 
  and    count(*) = 2 --optional - only if there's exactly two;

ID   DSC      MIN(VAL)   MAX(VAL)   
   2 POSNEG           -1          1


Is this answer out of date? If it is, please let us know via a Comment

More to Explore

SQL

The Oracle documentation contains a complete SQL reference.