我有一个表格(SPG),其中包含人员(DonorID),捐赠日期(DonateDate)和捐赠地点(Center)。我想找到捐赠的日期和地点(简单),然后是下一次捐赠的日期和地点,两个日期之间的间隔。
我使用了一个SELECT子查询,该子查询为我提供了下一个日期(NextDate),但是我随后无法获得匹配的Center:
SELECT SPG.DonorID,
SPG.DonateDate,
SPG.Center AS Center1,
(SELECT Min(DonateDate) as MinDate
FROM SPG As A
WHERE SPG.DonorID = A.DonorID
AND A.DonateDate > SPG.DonateDate) AS NextDate,
[NextDate]-[DonateDate] AS Gap
FROM SPG
GROUP BY SPG.DonorID, SPG.DonateDate, SPG.Center
HAVING ((((SELECT Min(DonateDate) as MinDate
FROM SPG As A
WHERE SPG.DonorID = A.DonorID
AND A.DonateDate > SPG.DonateDate))<>""))
ORDER BY SPG.DonorID, SPG.DonateDate;
我有一个不同的INNER JOIN查询,该查询为我提供了中心,但它返回了所有将来的捐赠,而不仅仅是下一个捐赠:
SELECT A.DonorID,
A.DonateDate,
A.Center,
Min(B.DonateDate) AS NextDate,
B.Center,
[B].[DonateDate]-[A].[DonateDate] AS Gap
FROM SPG AS A INNER JOIN SPG AS B ON A.DonorID = B.DonorID
WHERE B.DonateDate > A.DonateDate
GROUP BY A.DonorID,
A.DonateDate,
A.Center,
B.Center,
B.DonateDate-A.DonateDate;
基本上,我似乎无法将子查询中的Min()命令与从JOIN中返回多于字段结合起来。
(请原意使用不同的符号-大量复制和粘贴试验代码)
答案 0 :(得分:2)
这里的SQL神之一可能知道一种更清洁的方法,但这就是我目前所拥有的:
select
s1.donorid,
s1.donatedate,
s1.center as center1,
(
select min(s2.donatedate)
from spg s2
where s1.donatedate < s2.donatedate and s1.donorid = s2.donorid
) as nextdate,
(
select s2.center
from spg s2
where
s1.donorid = s2.donorid and
s2.donatedate =
(
select min(s3.donatedate)
from spg s3
where s1.donatedate < s3.donatedate and s1.donorid = s3.donorid
)
) as center2,
nextdate - s1.donatedate as gap
from
spg s1
order by
s1.donorid,
s1.donatedate
如果您仅在捐赠日期为“下一个”的记录之后,也许:
select
s1.donorid,
s1.donatedate,
s1.center as center1,
(
select min(s2.donatedate)
from spg s2
where s1.donatedate < s2.donatedate and s1.donorid = s2.donorid
) as nextdate,
(
select s2.center
from spg s2
where
s1.donorid = s2.donorid and
s2.donatedate =
(
select min(s3.donatedate)
from spg s3
where s1.donatedate < s3.donatedate and s1.donorid = s3.donorid
)
) as center2,
nextdate - s1.donatedate as gap
from
spg s1
where exists
(select 1 from spg s2 where s1.donorid = s2.donorid and s1.donatedate < s2.donatedate)
order by
s1.donorid,
s1.donatedate
我听说您喜欢相关子查询...