-1

enter image description here

From the input data, I need to rank the id. The data is order by time ascending.

Example: id number 421492036 has two record with code '05' and is ordered by time ascending.

The ID 421492036 has same code 05 and is the first two records in the table.

So its rank should be 1 in Output 1 table.

In Output 2 table we need to take the id 421492036 first record based on time.

Is it possible to get like this?

2
  • 2
    Please do not upload images of code/data/errors when asking a question. Commented Aug 26, 2022 at 15:07
  • 3
    Also what are you really using, SQL Server 2005 or 2008? Both are also completely unsupported, for 6 and 3 years respectively; it is long past time you upgraded regardless of which you are actually using. Commented Aug 26, 2022 at 15:07

2 Answers 2

1

According to the SQL Server Documentation, DENSE_RANK() is available on all supported versions of SQL Server. If you upgrade to one of the current versions you can run the query:

select max(id), max(code), max(time), rk
from (
  select t.*, dense_rank() over(order by time) as rk from t
) x
group by rk
Sign up to request clarification or add additional context in comments.

Comments

0

You can do the TOP 1 WITH TIES to get the first row only:

create table #t_id(id int, code varchar(30), time datetime)
insert into #t_id (id, code, time)
select 1, '05', '20200101'
union all
select 1, '05', '20200102'
union all
select 3, '05', '20200101'


select TOP 1 WITH TIES *
from #t_id t
ORDER BY (SELECT COUNT(*) FROM #t_id t2 WHERE t2.id = t.id AND t2.time < t.time)

COUNT(*) FROM #t_id t2 WHERE t2.id = t.id AND t2.time < t.time can be used to do the RANKing the '2005 way

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.