首页 文章

帮助sql join

提问于
浏览
2

我有两张 table :

表1:ID,PersonCode,名称,

表2:ID,Table1ID,Location,ServiceDate

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

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

4 回答

  • 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

    使用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
    

相关问题