帮助sql join

时间:2008-10-31 16:45:40

标签: sql sql-server

我有两张桌子:

表1: ID,PersonCode,名称,

表2: ID,Table1ID,位置,ServiceDate

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

我想要做的是返回Table1.PersonCode,Table1.Name,Table2.Location,Table2.ServiceDate,我不想要所有行,在表2中我只对最近ServiceDate的行感兴趣对于每个位置。我该怎么做呢?

4 个答案:

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

答案 1 :(得分:0)

使用MAX(ServiceDate)

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

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