如何获得具有T-SQL的一组值的首次出现
在下面有一个SQL Server DB表,我如何获取与第一次出现一系列值(Tablea和TableB_S已用户ID链接)相关的数据 - 我需要第一次出现isActive = 1的最后一个系列
value(表中的第五行,1000 | 1 | 2022-02-18 10:23:01):
tableb_s
userId | iSARTIVE | DATE |
---|---|---|
1000 | 0 | 2021-10-11 13:23 :00 |
1000 | 0 | 2021-11-11 15:23:12 |
1000 | 1 | 2021-11-10 12:23:32 |
1000 | 0 | 2022-01-02 09:23:56 |
1000 | 1 | 2022-02-02-18 10:23:011111 |
1000 | 1 | 2022-02-22 13:23:12 |
1000 | 1 | 2022-03-23 18:23:13 |
下面的查询返回与值isactive = 1
(1000)返回的数据 。
select a.*, ca.UserId, ca.Date
from TableA a
cross apply (select top 1 s.UserId, s.Date
from TableB_S s where s.UserId = a.UserId
order by s.Date desc) ca
|
| 1000 | 1 | 2022-02-18 10:23:01 |
Having a SQL Server DB table below how can I get the data related to the first occurrence of a series of values (TableA and TableB_S have UserId linked) - I need to get the first occurrence of the last series of IsActive = 1
value (the 5th row in the table, 1000 |1 | 2022-02-18 10:23:01):
TableB_S
UserId | IsActive | Date |
---|---|---|
1000 | 0 | 2021-10-11 13:23:00 |
1000 | 0 | 2021-11-11 15:23:12 |
1000 | 1 | 2021-11-10 12:23:32 |
1000 | 0 | 2022-01-02 09:23:56 |
1000 | 1 | 2022-02-18 10:23:01 |
1000 | 1 | 2022-02-22 13:23:12 |
1000 | 1 | 2022-03-23 18:23:13 |
The query below returns the data related to the last occorrence of the value IsActive = 1
(1000 | 1 | 2022-03-23 18:23:13)
select a.*, ca.UserId, ca.Date
from TableA a
cross apply (select top 1 s.UserId, s.Date
from TableB_S s where s.UserId = a.UserId
order by s.Date desc) ca
How to get this data ?
| 1000 | 1 | 2022-02-18 10:23:01 |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的逻辑是“对于每个用户获取启动一系列1的行(即,用户的日期顺序的上一行为零或不存在),那么该集合获得最高日期”。
The logic here is "for each user get the set of rows which start a series of 1's (ie, the previous row in date order for the user is a zero, or doesn't exist), then of that set get the highest date".