在两个条件(用户名THEN日期)上联接两个表

时间:2020-08-24 09:51:53

标签: sql

我有两个非常简单的表,第一个是每个用户ID的价格(按用户ID分组),然后是价格

select userid, price, min(auditdate) as Date from appeal_Audit
group by userid, price order by min(auditdate)

返回的表格如下(请注意,每个用户ID有多个价格)

--------------------------------
| User ID | Price | Audit Date |
--------------------------------
| 5555555 | 1000  | 2020-06-29 |
| 5555555 | 9999  | 2020-08-01 |
| 3333333 | 1000  | 2020-07-17 |

和一个包含用户详细信息的表,例如用户的用户ID,课程ID和他们从Signupstatus 100到110的日期

select
ROW_NUMBER() over (partition by UserId order by auditdate desc) as RowNo, userid, Courseid, auditdate
from (select 
userdetails_Audit.userid,
userdetails_Audit.SignupStatus,
lag(userdetails_audit.signupstatus) over (partition by userdetails_audit.userid order by userdetails_audit.auditdate) as OldSignupStatus,
case when userdetails_audit.SignupStatus > lag(userdetails_Audit.SignupStatus) over (partition by userdetails_audit.userid order by userdetails_audit.auditdate) then 1 else 0 end as Flag,
userdetails_audit.CourseId,
userdetails_audit.auditdate
from UserDetails_Audit
where userdetails_audit.SignupStatus >= 100) t1
where t1.flag = 1

哪个返回一个表,如

| Row No  | UserID | Course ID | AuditDate
------------------------------------------------
|       1 | 5555555  |      23 |   2020-06-27 |
|       2 | 5555555  |      57 |   2020-08-03 |
|       1 | 3333333  |      40 |   2020-07-19 |

我想知道如何首先通过Userid加入这两个表,然后在有多个案例的情况下(例如,它们两次进入状态110,因此有两个不同的价格,它们按日期联接,它们也最接近) )。任何想法或想法都会有所帮助!

我的理想结果是重复使用userid。基本上

USER ID | Price | Course ID | Min Date   |
5555555 | 9999  | 23        | 2020-06-27 |
5555555 | 1000  | 57        | 2020-08-01 |
3333333 | 1000  | 40        | 2020-07-17 |

0 个答案:

没有答案