SQL 基于特定字段值的选择

SQL selection based on a particular field value

我有 table 个人和他们的 table 地址。一个人可以有多个地址,但每个地址都附有生效日期。

我想 link 人和地址到他们最大的生效日期,我坚持下面附上的查询。我得到的只是整个 table 中的最大生效日期。请注意,这是角色扮演游戏,所以日期像数字一样存储,例如今天是 YYYYMMDD 格式的 20180831 (2018-08-31)。

 SELECT 
   PERSON.ID, PERSON.NAME, ADDRESS.ID, ADDRESS.ADD1
 , ADDRESS.ADD2, ADDRESS.CITY 
   FROM PERSON
   LEFT JOIN 
     (
      SELECT * 
        FROM ADDRESS
          WHERE EFF_DATE IN (SELECT MAX(EFF_DATE) FROM ADDRESS)
     ) AS A
   ON PERSON.ID = A.ID

我知道问题出在 WHERE 子句中,但我正在画一个空白。

你需要在 table person 和 table address 之间使用一个 LEFT OUTER JOIN,添加地址必须匹配最后一个 eff_date.

你没有说什么是数据库,但考虑到你将其标记为 RPG,我假设是 DB2:

with d as (
  select person_id, max(eff_date) as max_date 
    from address 
    group by person_id
)
select p.*
  from person p
  left join address a on p.id = a.person_id
    and (a.person_id, a.eff_date) in (
      select person_id, max_date from d
    )

IRL 我会查看最近的地址。

create view recentaddress as 
    select a.* from address a 
      join ( 
       select address.id, max(eff_date) md from address
        group by address.id 
        ) as b 
        on a.id = b.id and a.eff_date= b.md    

那你可以简单的查询人和最近的地址

select * from person a left join recentaddress b on a.person_id = b.id

或者您可以构建一个一体机。

select * from person a join (

        select a.* from address a 
          join ( 
           select address.id, max(eff_date) md from address
            group by address.id 
            ) as b 
            on a.id = b.id and a.eff_date= b.md    
) as address on a.person_id = address.id

Impaler 有一个很好的解决方案,但我会通过像这样删除子查询来改进它:

with d as (
  select person_id, max(eff_date) as max_date 
    from address 
    group by person_id
)
select p.*
  from person p
  left join d on p.id = d.person_id
  left join address a 
    on p.id = a.person_id and a.eff_date = d.max_date