【问题标题】:Help with sql joinsql连接帮助
【发布时间】:2008-10-31 16:45:39
【问题描述】:

我有两张桌子:

表 1: ID、PersonCode、姓名、

表 2: ID、Table1ID、位置、服务日期

我有一个查询在 table1.ID = table2.Table1ID where PersonCode = 'XYZ' 上将表 1 连接到表 2

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

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    类似这样的:

    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
    

    【讨论】:

    • 为什么要左连接?我认为 INNER JOIN 就足够了吗?我会修改您的查询 - 请在下面查看我的答案
    • 对不起,我正在用左连接解决另一个问题 - 已编辑
    【解决方案2】:

    使用 MAX(服务日期)

    【讨论】:

      【解决方案3】:

      试试:

      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
                               );
      

      【讨论】:

        【解决方案4】:

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

        【讨论】: