2008-10-31 83 views
2

我有两个表:帮助与SQL连接

表1: ID,PersonCode,名称,

表2: ID,Table1ID,地点,ServiceDate

我有一个查询将表1添加到table1.ID = table2.Table1ID其中PersonCode ='XYZ'

我想要做的是返回Table1.PersonCode,Table1.Name,Table2.Location,Table2.ServiceDate,我不想要所有的行,在表2中,我只对t感兴趣他为每个位置排列最近的ServiceDate。我会如何去做这件事?

回答

3

事情是这样的:

SELECT 
    Table1.PersonCode, Table1.Name, Table2.Location, MAX(Table2.ServiceDate) 
FROM 
    Table1 
    INNER JOIN Table2 on Table1.ID = Table2.Table1ID 
WHERE 
    TABLE1.PersonCode = 'XYZ' 
GROUP BY 
    Table1.PersonCode,Table1.Name, Table2.Location 
+0

为什么LEFT JOIN?我认为INNER JOIN是充足的吗? 我会修改您的查询 - 请参阅我的回答下面 – 2008-10-31 17:01:02

0

使用MAX(ServiceDate)

0

尝试:

select Table1.PersonCode,Table1.Name, Table2.Location, Table2.ServiceDate 
from Table1 
join Table2 on table1.ID = table2.Table1ID 
where table1.PersonCode = 'XYZ' 
and table2.ServiceDate = (select max(t2.ServiceDate) 
          from table2 t2 
          where t2.table1ID = table2.table1ID 
          and t2.location = table2.location 
         ); 
0

我会用一个INNER JOIN并选择第一个记录,在下令在反向记录基于Table2.ServiceDate的时间顺序。

SELECT TOP 1 
    Table1.PersonCode, Table1.Name, Table2.Location, Table2.ServiceDate 
FROM 
    Table1 
    INNER JOIN Table2 on Table1.ID = Table2.Table1ID 
WHERE 
    TABLE1.PersonCode = 'XYZ' 
ORDER BY Table2.ServiceDate DESC 
GROUP BY 
    Table1.PersonCode,Table1.Name, Table2.Location