需要从Table2中选择2行,并与Table1连接。见说明

时间:2016-01-03 14:49:29

标签: 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-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

我需要选择Table1中的所有列以及Table2中的第一个和最后一个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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您可以group by表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 ...