如何根据组的第一个值连接两个表

How to join two tables based on FIRST VALUE of a group

Objective: 我想根据按 [= 排序的订阅 ID 列分组的 Id 列的第一个值加入两个 tables 39=]列。

情况:

Table1 看起来像这样:

id  channel trx_date
123 organic 01/01/2019 05:00:00
234 direct  01/01/2019 05:01:00
987 add     01/01/2019 10:00:00
654 organic 01/01/2019 10:15:00

Table2:

subscription_id id  os      created_at
sub890         123  mac     01/01/2019 05:00:01
sub890         234  mac     01/01/2019 05:01:01
sub111         987  windows 01/01/2019 10:00:01
sub111         654  mac     01/01/2019 10:20:01

我需要将 table 2 中最早的 ID 按订阅 ID 分组并将其与 Table 1 进行内部连接。 所以在这个例子中,我的输出是

subscription_id id  os      created_at id       channel trx_date
sub890          123 mac     01/01/2019 05:00:01 organic 01/01/2019 05:00:00
sub111          987 windows 01/01/2019 10:00:01 add     01/01/2019 10:00:00

我尝试了什么: 我考虑过使用 FIRST_VALUE 但我不知道如何连接它们

SELECT t1.*, 
  t2.subscription_id,
  t2.os,
  t2.created_at, 
  FIRST_VALUE(t2.id) OVER (PARTITION BY t2.subscription_id ORDER BY t2.created_at ASC) as Min_Id
FROM table1 t1
INNER JOIN table2 t2 ON t1.id = t2.Min_id

Fiddle 信息:

CREATE TABLE table1
    ([id] varchar(13), [channel] varchar(50), [trx_date] Datetime)


INSERT INTO table1
VALUES
    ('123', 'organic', '2019-01-01 05:00:00'),
    ('234', 'direct', '2019-01-01 05:01:00'),
    ('987', 'add', '2019-01-01 10:00:00'),
    ('654', 'organic', '2019-01-01 10:15:00')

CREATE TABLE table2
    ([subscription_id] varchar(13),[id] varchar(13), [os] varchar(10), [created_at] Datetime)

INSERT INTO table2
VALUES
    ('sub890', '123', 'mac', '2019-01-01 05:00:01'),
    ('sub890', '234', 'mac', '2019-01-01 05:01:01'),
    ('sub111', '987', 'windows', '2019-01-01 10:00:01'),
    ('sub111', '654', 'mac', '2019-01-01 10:20:01')

显然,由于 ON 子句,这不起作用。这种情况是否需要 row_number 函数来代替交叉应用?有更好的方法吗? FIRST_VALUE 函数使用错误吗?

applytop (1) 一起使用:

SELECT t1.*, t2.subscription_id, t2.id, t2.os, t2.created_at
FROM table1 t1 CROSS APPLY
     (SELECT TOP (1) t2.*
      FROM table2 t2 
      WHERE t1.id = t2.id
      ORDER BY t2.created_at ASC
     ) t2

您可以将 row_number() 与 create_at 日期之前的订单一起使用,这将采用第一个 ID

with cte as
(
select *,row_number() over(partition by subscription_id  order by created_at) rn
  from tabl2
) select cte.*,t1.* from cte 
       join table1 t1 on cte.id =t1.id
  where cte.rn=1

demo link

subscription_id id  os    created_at           rn   id  channel  trx_date
sub890          123 mac   01/01/2019 05:00:01   1   123 organic 01/01/2019 05:00:00
sub111          987 windows 01/01/2019 10:00:01 1   987 add     01/01/2019 10:00:00