加入两个表,只从第二个表中获取最近的条目

时间:2016-10-01 15:24:03

标签: sql firebird

我需要制作这个火鸟查询,请帮助

我有两张桌子:

表1:客户端

ID, NAME, TEL, ADRESS, EMAIL

表2:CRM_INTERACTIONS

ID, CLIENT_ID, DATE, INTERACTION_TYPE

我需要检索客户端表的所有字段以及表2的2列:该客户端的最后一个interaction_type加上日期,以便视图如下所示:

ID, NAME, TEL, ADRESS, EMAIL, DATE_OF_LAST_INTERACTION, INTERACTION_TYPE

1, JOHN, 555555,1TH ST, John@gmail.com, 01/10/2016, phone call

1 个答案:

答案 0 :(得分:1)

我认为firebird 3+有select c.*, ci.* from client c left join (select ci.*, row_number() over (partition by client_id order by date desc) as seqnum from crm_interactions ci ) ci on c.id = ci.client_id and seqnum = 1; ,所以你可以这样做:

select c.*, ci.*
from client c left join
     crm_interactions ci
     on c.id = ci.client_id left join
     (select ci.client_id, max(date) as maxdate
      from crm_interactions ci
      group by ci.client_id
     ) cci
     on ci.client_id = cci.client_id and ci.date = cci.maxdate;

在早期版本中,您将使用传统SQL执行此操作。这是一种方式:

insert into usertable ( phone ) values ( '12345' );
insert into category ( userid, cat1, cat2 ) select u.id , 'cat1', 'cat2' from usertable u where u.phone='12345';
insert into tracking ( userid, track1 ) select id, 'track1' from usertable u where u.phone='12345';