1

I have this data on SQL Server

emp_id   date           seq
1        2020-10-01     1
1        2020-10-02     2
1        2020-10-05     1
1        2020-10-06     2
2        2020-10-01     1
2        2020-10-02     2
2        2020-10-03     3

I want to transform the data to max row for every sequence like this:

emp_id   date           seq
1        2020-10-02     2
1        2020-10-06     2
2        2020-10-03     3

I tried using max(seq) but the return only the max sequence for every employee, not for every sequence

0

4 Answers 4

1

Use LEAD() window function to get the next value of seq of each row and fliter out the rows where the next value of seq is greater than the current one:

SELECT emp_id, date, seq
FROM (
  SELECT *, LEAD(seq) OVER (PARTITION BY emp_id ORDER BY date) next_seq
  FROM tablename
) t
WHERE seq > next_seq OR next_seq IS NULL

See the demo.

Results:

emp_id date seq
1 2020-10-02 2
1 2020-10-06 2
2 2020-10-03 3
Sign up to request clarification or add additional context in comments.

Comments

1

Yet another option is WITH TIES in concert with the window function dense_rank()

Example

Select top 1 with ties * 
 From  YourTable
 Order By dense_rank() over (partition by emp_id order by seq desc)

Results

emp_id  date        seq
1       2020-10-02  2
1       2020-10-06  2
2       2020-10-03  3

Comments

1

You simply filter DENSE_RANK = 1

DENSE_RANK gives you tied results (same row-number for same order), ROW_NUMBER is non-tied

SELECT *
FROM (
    SELECT *,
        rn = DENSE_RANK() OVER (PARTITION BY t.emp_id ORDER BY seq DESC)
    FROM yourTable t
) t
WHERE rn = 1;

1 Comment

@OctavianWR . . . If you are going to use window functions (which are unnecessary) then this is the better and clearer approach.
-1

One method uses a correlated subquery:

select t.*
from t
where t.seq = (select max(t2.seq) from t t2 where t2.emp_id = t.emp_id);

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.