【问题标题】:Pull up the most recent record including joining 2 tables and filters提取最近的记录,包括加入 2 个表和过滤器
【发布时间】:2016-10-06 16:16:12
【问题描述】:

我看过很多关于拉起最近记录的帖子。我找不到包含加入另一个表和过滤器的内容。

我需要的是有关最近创建的文档(记录)的信息,但前提是它符合某些标准。另外,我需要从另一个表中提取一些数据。

s504计划表

    Student ID   |   Firstname   |   Startdate   |   Status
    ----------       ---------       ---------       ------
    111111            Johnny         1/5/2015          F
    222222            Sue            4/7/2016          I
    333333            Barb           2/5/2016          F
    111111            Johnny         2/1/2016          F

病例表

    Student ID   |   School   |   
    ----------       ------
    111111           Franklin
    222222           Eisenhower
    333333           Franklin

而且我希望看到的结果只是最近的文档,其中文档的状态为 F...

    Student ID  |  Firstname  |  Startdate  |  Status  |   School
    ----------     ---------     ---------     ------      ------
    111111          Johnny       2/1/2016        F         Franklin
    333333          Barb         2/5/2016        F         Franklin

谢谢!

【问题讨论】:

    标签: sql sql-server-2005


    【解决方案1】:

    你可以使用内连接和where

    select 
        a.Student_ID
      , a.Firstname
      , a.Startdate
      , a.Status
      , b.School
    from s504Plans  as a
    inner join Cases  as b on  a.Student_ID = b.Student_ID
    inner join ( select Student_ID, max(Startdate ) as max_startdate
                from s504Plans
                group by Student_ID) t 
               on ( a.Student_id = t.Student_id and a.Startdate = t.max_startdate)
    where a.Status = 'F'
    

    【讨论】:

    • 谢谢!我不确定操作的顺序以及它是否会不管状态为 FIRST 是否会拉出最新的,然后删除任何标记为 Inactive 的最新的,这可能会让一些孩子离开。我现在就试试看!
    • 我最终收到了一些错误消息。消息 8155,级别 16,状态 2,第 7 行没有为“t”的第 2 列指定列名。消息 207,级别 16,状态 1,第 7 行无效的列名称“开始日期”。
    • 我一遍又一遍地查看,并没有看到我的错误类型。我会继续寻找!
    • @bosstone75 缺少 max(Startdate) 的别名 .. 我已经更新了答案
    • 哇哦!成功!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2021-04-24
    • 2022-01-23
    • 2015-11-05
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多