Return 第一次约会和之前的约会
Return first date and previous dates
有一个 custid 有 3 个日期。
我想 return 第一个日期,然后是上一个日期。
数据应如下所示:
custid first previous
11 2019-06-10 2019-06-15
11 2019-06-10 2019-07-10
我做到了,但我不能把它放在第二行。
SELECT A.PersonID ,min(a.date) as first,b.date as previous,c.date as previous from Persons as a
INNER JOIN (select PersonID ,date from Persons) b
on a.PersonID
=b.PersonID AND
a.date<
b.date
INNER JOIN (select PersonID ,date from Persons) c
on b.PersonID=
c.PersonID
AND b.date<
c.date
我得到的输出:
personid first previous previous
11 2019-06-10 2019-06-15 2019-07-10
我希望它看起来像:
custid first previous
11 2019-06-10 2019-06-15
11 2019-06-10 2019-07-10
您不需要添加第三个内部联接 table。由于您将 min() 与其他列一起使用,因此应该伴随分组依据。
select
a.PersonID as custid,
min(a.date) as first,
b.date as previous
from
Persons as a
inner join Persons b on a.PersonID = b.PersonID and b.date > a.date
group by a.PersonID, b.date
有一个 custid 有 3 个日期。
我想 return 第一个日期,然后是上一个日期。
数据应如下所示:
custid first previous
11 2019-06-10 2019-06-15
11 2019-06-10 2019-07-10
我做到了,但我不能把它放在第二行。
SELECT A.PersonID ,min(a.date) as first,b.date as previous,c.date as previous from Persons as a
INNER JOIN (select PersonID ,date from Persons) b
on a.PersonID
=b.PersonID AND
a.date<
b.date
INNER JOIN (select PersonID ,date from Persons) c
on b.PersonID=
c.PersonID
AND b.date<
c.date
我得到的输出:
personid first previous previous
11 2019-06-10 2019-06-15 2019-07-10
我希望它看起来像:
custid first previous
11 2019-06-10 2019-06-15
11 2019-06-10 2019-07-10
您不需要添加第三个内部联接 table。由于您将 min() 与其他列一起使用,因此应该伴随分组依据。
select
a.PersonID as custid,
min(a.date) as first,
b.date as previous
from
Persons as a
inner join Persons b on a.PersonID = b.PersonID and b.date > a.date
group by a.PersonID, b.date