按ID分组但抓取与Id相关的第一个日期

时间:2013-08-30 14:06:56

标签: sql

目标:获取唯一的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

2 个答案:

答案 0 :(得分:3)

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

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

这假定DateCreated实际上存储为datedatetime

您可以在子查询中使用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;

答案 1 :(得分: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;