SQL to get the device number of the user's first login

SQL obtains the device number of the user's first login.
There is a table as follows:
p_id d_id event_date g_p
1 2 2019-08-01 5
1 2 2019-09-01 8
2 3 2020-01-01 1
3 1 2019-03-01 9
3 5 2020-01-03 6
Get the d_id of the device that p_id logs in for the first time, and the returned result is as follows:
p_id d_id
1 2
2 3
3 1

Answer:
First of all, I think of the row_number function for sorting, and then get the first-ranked data. The query SQL is as follows:
Step 1: Group and sort the p_id field

SELECT p_id
      ,d_id
      ,event_date
      ,row_number () over (PARTITION BY p_id ORDER BY event_date) AS rn
  FROM test_01

Result:
p_id d_id event_date rn
1 2 2019-08-01 1
1 2 2019-09-01 2
2 3 2020-01-01 1
3 1 2019-03-01 1
3 5 2020-01-03 2

Step 2: Obtain data with rn=1

SELECT p_id
      ,d_id
  FROM(
       SELECT p_id
             ,d_id
             ,event_date
             ,row_number ( ) over ( PARTITION BY p_id ORDER BY event_date ) AS rn
         FROM test_01
       ) a
 WHERE rn = 1;

Result:
p_id d_id
1 2
2 3
3 1

 

Remarks: create table and data
create table test_01 (p_id int,d_id int,event_date date,g_p int);

insert into test_01 values(1,2,'2019-08-01',5);
insert into test_01 values(1,2,'2019-09-01',8);
insert into test_01 values(2,3,'2020-01-01',1);
insert into test_01 values(3,1,'2019-03-01',9);
insert into test_01 values(3,5,'2020-01-03',6);

 

Guess you like

Origin blog.csdn.net/debimeng/article/details/104098384