首页 > 解决方案 > 根据最近的日期选择行,包括唯一信息

问题描述

我找到了许多选择最近日期的解决方案,但是,当我这样做时,我无法成功地包含我的所有列,因为我有我希望包含的唯一数据。

这是我的原始查询:

select p.scode, u.scode, sq.dsqft0, sq.dtdate
from unit u
join property p on p.hmy = u.hproperty
join sqft sq on sq.hpointer = u.hmy
where p.hmy = 19

这将返回:

p.scode      u.scode      dsqft0           dtdate
-------------------------------------------------------------------
01200100     100          23879            1/1/1980 12:00:00 AM
01200100     100          19000            10/30/2017 12:00:00 AM
01200100     100          23879            11/1/2018 12:00:00 AM
01200100     200          33854            1/1/1980 12:00:00 AM
01200100     400          7056             1/1/1980 12:00:00 AM
01200100     400          12056            6/1/2015 12:00:00 AM

我只想接收每个 p.scode 和 u.scode 的最新条目,但是,我不想按 sq.dsqft0 分组 - 我只想接收该列中的最新条目p.scode/u.scode 行。

如果我从查询中删除 sq.dsqft0 列,我可以缩小到我想要的行,但我需要 sq.dsqft0 列中的信息。这是几乎有效的查询:

select p.scode,u.scode,max(sq.dtdate)as currentdate
from unit u
join property p on p.hmy=u.hproperty
join sqft sq on sq.hpointer=u.hmy
where p.hmy=19
group by p.scode,u.scode

这将返回:

p.scode      u.scode         currentdate
01200100     100             11/1/2018 12:00:00 AM
01200100     200             1/1/1980 12:00:00 AM
01200100     400             6/1/2015 12:00:00 AM

这些是正确的行,但是,如果我包含 sq.dsqft0,我必须将它包含在 group by 语句中,它会返回 sq.dsqft0 列不匹配的其他行。如果我输入这个:

select p.scode,u.scode,sq.dsqft0,max(sq.dtdate) as currentdate
from unit u
join property p on p.hmy=u.hproperty
join sqft sq on sq.hpointer=u.hmy
where p.hmy=19
group by p.scode,u.scode,sq.dsqft0

它返回这个:

p.scode      u.scode      dsqft0           dtdate
01200100     100          19000            10/30/2017 12:00:00 AM
01200100     100          23879            11/1/2018 12:00:00 AM
01200100     200          33854            1/1/1980 12:00:00 AM
01200100     400          7056             1/1/1980 12:00:00 AM
01200100     400          12056            6/1/2015 12:00:00 AM

标签: sql

解决方案


我的建议是使用子查询来查找最新数据,然后加入原始表以获得“dsqft0”:

select * from 
 ( select  p.scode,u.scode as uscode, current_date, dsqft0 
   from unit u
   join property p on p.hmy=u.hproperty
   join sqft sq on sq.hpointer=u.hmy
   where p.hmy=19 ) a
   join 
 (select p.scode,u.scode as uscode ,max(sq.dtdate)as currentdate
  from unit u
  join property p on p.hmy=u.hproperty
  join sqft sq on sq.hpointer=u.hmy
  where p.hmy=19 
  group by p.scode,u.scode ) sub 
  on a.scode = sub.scode
  and a.uscode = sub.uscode
  and a.current_date  = sub_current_date

推荐阅读