根据最近日期选择行,包括唯一信息

时间:2018-11-14 17:05:24

标签: sql

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

这是我的原始查询:

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

1 个答案:

答案 0 :(得分:0)

我的建议是使用子查询查找最新数据,然后与原始表结合以获取“ 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