Skip to Main Content
  • Questions
  • Ignore results if a column has the same value

Breadcrumb

May 4th

Question and Answer

Chris Saxon

Thanks for the question, Gohulan.

Asked: October 08, 2022 - 3:25 am UTC

Last updated: October 10, 2022 - 4:24 pm UTC

Version: 12.1.0.2.0

Viewed 1000+ times

You Asked

Hi Tom,

I have written a SQL query to display results, the below is the query

SELECT TRANSACTION_ID, INVOICE_NO, MOBILE_NO, ITEM_AMOUT
FROM INVOICE_DAILY_DTS
WHERE DAILY_DTS != 200 AND INVOICE_SAM = 12;



When I am executing the above query, I am getting the below results

1) 11331133114, 154245, 077123456789, 579.5
2) 11331133114, 154245, 077123456789, 579.5
3) 11331133114, 154246, 077457852155, 780.4
4) 11331133114, 154245, 077123456789, 579.5
5) 11331133114, 154458, 077547822554, 900.0
6) 11331133114, 154245, 077123456789, 579.5
7) 11331133114, 154246, 077457852155, 780.4


If you see the above results table has multiple rows of data in the INVOICE_NO column, I suggest getting ignore 2,4,6 & 7th rows when executing the query.
Simple if the INVOICE_NO is duplicated only needs to get the first row of the result and ignore other results.

I am expecting the results are below, where it has ignored or excepted the results and showing the first row only of each INVOCIE_NO

1) 11331133114, 154245, 077123456789, 579.5
2) 11331133114, 154246, 077457852155, 780.4
3) 11331133114, 154458, 077547822554, 900.0

and Chris said...

Here are a couple of general approaches:

Number the rows in a subquery

Use row_number to assign these, then filter to the rows where this equals one:

with rws as (
  select invoice_id, ...
         row_number () over (
           partition by invoice_id
           order by sort_column
         ) rn
  from   invoice_daily_dts i
  where  ...
)
  select * from rws
  where  rn = 1;


https://blogs.oracle.com/sql/post/how-to-select-the-top-n-rows-per-group-with-sql-in-oracle-database

Group by invoice_id

Then aggregate all the other columns. To get the values from the first row in each group, use the KEEP ( DENSE_RANK FIRST ) clause:

select invoice_id, 
       min ( c1 ) keep (
         dense_rank first
         order by sort_column
       ), 
       min ( c2 ) keep (
         dense_rank first
         order by sort_column
       ),
       <etc.>
from   invoice_daily_dts i
where  ...
group  by invoice_id


https://db-oriented.com/2013/08/08/tip003/

Using a subquery is easier if you're selecting lots of columns. Grouping is better if it turns out you need values from rows other than the first in each group (e.g. MIN/MAX/AVG/...)

Rating

  (1 rating)

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

More to Explore

Analytics

Analytic SQL got you confused? Check out Connor McDonald's complete video course.