0

目标:获取唯一的 MembershipId 和与 MembershipId 相关的第一个日期。

我可以获得不同的 MembershipId,但我不确定获取与记录相关的日期的最佳方式。

IE。

1 : 12/1/12
1 : 12/2/12
2 : 12/1/12
3 : 12/1/12

应该返回

1 : 12/1/12
2 : 12/1/12
3 : 12/1/12

日期对于是否是同一天并不重要,只是很容易输入,重要的是它返回 ID 为 1 以及与该记录相关的第一个日期。

我将 2 个表网格化到一个临时表中,然后选择不同的 ID,但我很难过如何获取相关日期。

这是我到目前为止所拥有的:

select [MembershipId], [DateCreated]
INTO #StripeTemp
FROM fundingsources

UNION

select [UserId] as MembershipId, [DateInserted] as DateCreated
FROM FundingSourceCustomer

select distinct MembershipId
from #StripeTemp

Drop table #StripeTemp
4

2 回答 2

3

我想你想要一个基本的聚合查询。这是一张表的版本:

select [MembershipId], min([DateCreated]) as FirstDateCreated
INTO #StripeTemp
FROM fundingsources
GROUP BY MembershipID;

这假定DateCreated实际存储为 a dateor datetime

您可以通过union all在子查询中使用来对两个表执行此操作,因此不需要临时表:

select [MembershipId], min([DateCreated]) as FirstDateCreated
FROM (select MemberShipId, DateCreated
      from fundingsources
      union all
      select MemberShipId, DateInserted
      from fundingsourcecustomer
     ) t
GROUP BY MembershipID;
于 2013-08-30T14:10:57.310 回答
0

根据每个 id 的行数,在 UNION 之前预聚合可能更有效:

SELECT MembershipId, MIN(DateCreated) AS FirstDateCreated
FROM (SELECT MembershipId, MIN(DateCreated) AS DateCreated
      FROM fundingsources
      GROUP BY MembershipId 
      UNION ALL
      SELECT MembershipId, MIN(DateCreated) AS DateCreated
      FROM fundingsourcecustomer
      GROUP BY MembershipId 
     ) t
GROUP BY MembershipID;
于 2013-08-30T14:44:27.510 回答