Share via

Min date for repeated values

Shambhu Rai 1,411 Reputation points
2022-04-20T16:07:43.867+00:00

Hi Expert,
I wanted to fetch min date records where value column data is repeated

create table test3
(newdate datetime,status varchar(22),value varchar(22)
)
insert into test3
values

('2021-06-16 09:44:47.000', 'Newthree', '6 - 1'),
('2022-04-01 18:00:57.000', 'Newthree', '6 - 1'),
('2022-03-28 15:58:40.000', 'Newtwo', '3 - Test'),
('2022-03-31 15:20:17.000', 'Newtwo', '8 - MO'),
('2022-04-01 18:20:27.000', 'Newtwo', '8 - MO'),
('2022-03-28 12:48:46.000', 'Newone', '4 - Dead'),
('2022-04-01 18:20:28.000', 'Newone', '7 - Lost')

expected output
('2021-06-16 09:44:47.000', 'Newthree', '6 - 1')
('2022-03-28 15:58:40.000', 'Newtwo', '3 - Test')
('2022-03-31 15:20:17.000', 'Newtwo', '8 - MO'),
('2022-03-28 12:48:46.000', 'Newone', '4 - Dead'),
('2022-04-01 18:20:28.000', 'Newone', '7 - Lost')

Azure SQL Database
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

Naomi Nosonovsky 8,906 Reputation points
2022-04-20T16:20:00.083+00:00

Why do you continue to ask the same (or almost the same) question over and over?

;with cte as (select *, ROW_NUMBER() over (partition by [Status], [Value] ORDER BY NewDate) as Rn from dbo.Test)

select * from cte where Rn = 1 -- minimum datetime value for same status and value

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Viorel 127K Reputation points
    2022-04-20T17:44:45.927+00:00

    Check this query too:

    select min(newdate) as newdate, status, value
    from test3
    group by status, value
    order by newdate
    

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

  2. Shambhu Rai 1,411 Reputation points
    2022-04-20T17:16:44.68+00:00

    modified the query littlebit
    ;with cte as (select *, ROW_NUMBER() over (partition by status, [Value] ORDER BY NewDate) as Rn from dbo.Test3)

    select * from cte where Rn = 1 -- minimum datetime value for same status and value

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.