1

I'm looking to get distinct rows with a start and end date from a table with structure below. I dont want duplicate rows with same start and end month. Please note that start and end date are NUMBER type here, not date.

tbl_app_ranges:
rg_id   start_month   end_month
105     200401        200409    
105     200401        200409    
110     200701        200712    
110     200701        200710     

What I want is the below result set

rg_id   start_month   end_month
105     200401        200409    
110     200701        200712    
110     200701        200710     

I know this can be done with analytics but not sure how. Is there a way to do this in pure SQL? I need the query to work against Oracle database.

1
  • 1
    Use DISTINCT/UNIQUE or a GROUP BY rg_id, start_month, end_month. Commented Nov 13, 2015 at 13:48

5 Answers 5

2
select distinct rgid,start_month,end_month from tbl_app_ranges;
Sign up to request clarification or add additional context in comments.

Comments

2

You can use GROUP BY rg_id, start_month, end_month in your query.

1 Comment

DISTINCT would internally do a GROUP BY. +1 for the answer though.
1

Try this:

SELECT DISTINCT start_month   , end_month 
FROM tbl_app_ranges;

SQL DISTINCT clause example would return each unique start month and end month combination.

Comments

1
select rg_id, start_month, end_month from tbl_app_ranges
group by end_month, start_month, rg_id

1 Comment

No need for the derived table.
0

You asked,

I know this can be done with analytics but not sure how.

If you want to do it in Analytics, then you could use ROW_NUMBER() analytic function.

select rg_id, start_month, end_month from (
select rg_id,
       start_month,
       end_month,
       ROW_NUMBER() OVER(PARTITION BY rg_id, 
                                      start_month, 
                                      end_month 
                         ORDER BY rg_id) rn        
from tbl_app_ranges)
WHERE rn = 1;

How the query works:

The ROW_NUMBER assigns an ordered row_number to each group as specified in the PARTITION BY clause. The sorting is taken care by ORDER BY clause. Thsi becomes the inner sub-query, the outer query filters the rows based on the row_number.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.