0

I have a table that has 3 columns. I do not want to repeat the row based on 2 columns that have the same values.

  |start_date(date)| end_date(date) |theDiff(integer)
  ---------------------------------------------------
  |2018-05-14      |  2018-05-18    |        5      |
  |2018-05-14      |  2018-05-18    |        10     |
  ---------------------------------------------------

Expected Output:

  |start_date(date)| end_date(date) |theDiff(integer)
  ---------------------------------------------------
  |2018-05-14      |  2018-05-18    |        5      |
  ---------------------------------------------------

I have many such rows and do not want them to repeat. I just want to add their first occurrence. I always want it to output the lower difference.

0

2 Answers 2

1

If I understand correctly you expect the first occurrence of all different (start_date, end_date).

You can use row_number() function and then select rows where row number = 1.

with x as
(
    select start_date, end_date, theDiff,
           row_number() over (partition by start_date, end_date order by start_date) rn
    from   tbl
)
select start_date, end_date, theDiff
from   x
where  rn = 1; 
start_date | end_date   | thediff
:--------- | :--------- | ------:
2018-05-14 | 2018-05-18 |       5

db<>fiddle here

You can move CTE to the FROM clause:

select start_date, end_date, theDiff
from
    (
        select start_date, end_date, theDiff,
               row_number() over (partition by start_date, end_date order by start_date) rn
        from   tbl
    ) x
where  rn = 1; 
0
1

It is not clear how the resulting theDiff is determined, some alternative AGGREGATING functions:

-- diff between max and min
SELECT start_date, end_date, MAX(thediff)-MIN(thediff)
FROM T
GROUP BY start_date, end_date

-- min value
SELECT start_date, end_date, MIN(thediff)
FROM T
GROUP BY start_date, end_date

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.