如何从我的两个不同 table 中找到日期差异

how to find date difference from two different table in mys

我有两张桌子

1)LEAD TABLE(有 3 列)

Lead_ID || Created_Date ||行业

2)ACCOUNTS TABLE(有 4 列)

Account_ID||Created_Date|| Revenue_Range|| Lead_ID

我如何获得创建潜在客户和创建帐户之间的平均天数

别在意数据乱七八糟的,我随便填的。 查询 returns leadId 和 lead.created_date 与 account.created_date 之间的天数差异。

查询:

create table Leads
(
    leadId int not null,
    created_date datetime,
    industry varchar(10),
    PRIMARY KEY (leadId)
);

create table Accounts
(
    accountId int not null,
    created_date datetime,
    revenue_range varchar(10),
    leadId int not null,
    FOREIGN KEY (leadId) REFERENCES Leads(leadId)
);

insert into Leads
values 
(1, '2020-01-01', 'a'),
(2, '2020-01-02', 'b'),
(3, '2020-01-03', 'c'),
(4, '2020-02-01', 'd'),
(5, '2020-03-01', 'e');

insert into Accounts
values 
(1, '2020-01-03', '1k', 1),
(2, '2020-03-10', '2k', 5),
(3, '2020-02-03', '3k', 2);

select 
 -- l.leadId,
 -- l.created_date as LeadCreatedDate,
 -- a.created_date as AccountCreatedDate,
 -- ABS is used because it returns with minus sign
 AVG(ABS(DATEDIFF(l.created_date, a.created_date))) as AvgDifferenceInDaysBetweenCreation
from Leads as l
inner join Accounts as a
on l.leadId = a.leadId;

您可以在 SQLize Online

试用