1

I have a table something like this:

CREATE TABLE [dbo].[Test3](
[UserId] [int] NULL,
[RoleId] [int] NULL,
[lastDate] [date] NULL
) ON [PRIMARY]

INSERT INTO [dbo].[Test3]([UserId],[RoleId],[lastDate])
VALUES
(1,1,'2019-02-02'),
(1, NULL, '2019-02-02'),
(1, 2, '2019-02-03'),
(2, 1, '2019-02-05'),
(2, 1, '2019-02-02'),
(2, 1, '2019-02-02'),
(3, 3, '2019-02-02'),
(3, NULL, '2019-02-02')

How do I set row number and max lastdate a list of users who have the same "userid"? I need output should be look like this.

rownumber  userid   RoleId   lastdate
1          1        2       2019-02-03
2          1        1       2019-02-03
3          1        NULL    2019-02-03
1          2        1       2019-02-05
2          2        1       2019-02-05
3          2        1       2019-02-05
1          3        3       2019-02-02
2          3        NULL    2019-02-02
Tom
  • 67
  • 4

2 Answers2

2

You can use row_number and max with window functions

I think this bellow code can help you.

SELECT ROW_NUMBER() OVER(PARTITION BY UserId ORDER BY RoleId DESC) AS ROWNUMBER,
   userid,
   roleid,
   MAX(lastDate) OVER(PARTITION BY userId) AS LAST
FROM   test3
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
Reza Jenabi
  • 3,884
  • 1
  • 29
  • 34
1

You can use row_number() & max() with window function :

select t.*,
       row_number() over (partition by userid 
                          order by (case when roleid is null then 2 else 1 end), 
                                    roleid desc
                         ) as rowno,
       max(lastdate) over (partition by userid) as lastdate
from table t;
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52