Sql server 需要从与表1连接的表2中选择2行。见说明

Sql server 需要从与表1连接的表2中选择2行。见说明,sql-server,Sql Server,例如,我有一个表1: ID Specified TIN Value DateCreated ---------------------------------- 1 0 tin1 45 2014-12-30 2 1 tin2 34 2013-01-05 3 0 tin3 23 2015-02-20 4 3 tin4 47 2013-06-04 5 3 tin5 12 2012-

例如,我有一个表1:

ID Specified TIN Value DateCreated
----------------------------------
1       0   tin1   45   2014-12-30
2       1   tin2   34   2013-01-05
3       0   tin3   23   2015-02-20
4       3   tin4   47   2013-06-04
5       3   tin5   12   2012-04-02
表2:

ID Table1ID RegistrationDate
----------------------------------
1       1      2015-10-12
2       2      2015-07-21
3       1      2015-11-26
4       1      2015-12-04
5       2      2015-09-18
我需要从表1中选择所有列,并在表2中选择第一列和最后一列RegistrationDate。答案应该是

ID Specified TIN Value DateCreated   FirstRegDate   LastRegDate
---------------------------------------------------------------
1       0   tin1   45   2014-12-30    2015-10-12    2015-12-04
2       1   tin2   34   2013-01-05    2015-07-21    2015-09-18
3       0   tin3   23   2015-02-20    NULL          NULL
4       3   tin4   47   2013-06-04    NULL          NULL
5       3   tin5   12   2012-04-02    NULL          NULL

您可以按表1中的所有列进行分组,并查找组的最小和最大注册日期:

select  ID
,       Specified
,       ... other columns from table1 ...
,       min(RegistrationDate)
,       max(RegistrationDate)
from    Table1 t1
left join
        Table2 t2
on      t1.ID = t2.Table1ID
group by
        ID
,       Specified
,       ... other columns from table1 ...

嗨,一个可能的解决方案可以类似于下面的伪查询(如果您可以准备我将修改的表以反映实际查询)

非常感谢。它正在工作)。我将接受这个答案,只要我达到15的声誉!
SELECT table1.*, inlineTable2.firstRegDate, inlineTable2.lastRegDate 
FROM Table1
LEFT JOIN
(
   SELECT
   Table1ID AS id,
   MIN(registrationDate) as firstRegDate,
   MAX(regsitrationDate) as lastRegDate
   FROM table2
   GROUP BY table1ID
) AS inlineTable2
ON table1.id = inlineTable2.id