SQL选择具有最新日期的属性列[关闭]

问题描述 投票:-6回答:2

我有一个包含多个租户的表,有些租户有另一个到期日期,表中的其余部分是每个租户都相同的。我想选择只有最新到期日的租户。

这是我的代码:

SELECT DISTINCT
property.scode AS "M nr",
tenant.scode AS "Contract nr",
unit.scode AS "Unit",
commamendments.DTSTART AS "Starting date",
sqft.DTDATE AS "Expiry date",
sqft.DSQFT0 AS "Area"


FROM 
property 
LEFT JOIN unit ON unit.hproperty = property.hmy
LEFT JOIN unitxref ON unitxref.hunit = unit.hmy
LEFT JOIN commamendments ON commamendments.hmy = unitxref.hamendment 
LEFT JOIN tenant ON tenant.hmyperson = commamendments.htenant
JOIN attributes ON attributes.HPROP = property.hmy
JOIN sqft ON sqft.hpointer = unit.hmy


WHERE property.scode = '481' 
AND sqft.DSQFT0 != '0'
AND ('9/30/2017 12:00:00 AM' BETWEEN  commamendments.DTSTART AND commamendments.DTEND)
ORDER BY   commamendments.DTEND`

作为输出我想要一个表

Mnr     Contract nr      Unit     Starting date    Expiry date    Area
481       1                1      9-10-2017         12-31-2018     400
481       2                2      8-10-2017         12-31-2019     500
.....

我现在收到的是:

Mnr     Contract nr      Unit     Starting date    Expiry date    Area
481       1                1      9-10-2017         12-31-2018     400
481       1                1      9-10-2017         09-20-2018     400
481       2                2      8-10-2017         12-31-2019     500
481       2                2      8-10-2017         1-31-2018      500
.....
sql
2个回答
1
投票

由于您没有指定正在处理的RDBMS和表模式,因此您可以执行以下操作:

SELECT t1.tenantId, t1.ExpiryDate
FROM tenants AS t1
INNER JOIN
(
   SELECT tenantId, MAX(ExpiryDate) AS LatestExpiryDate
   FROM tablename
   GROUP BY tenantId
) AS t1 ON t1.tenantId = t2.tenantId, t1.ExpiryDate = t2.LatestExpiryDate;

内部联接将为每个租户ID提供最新日期,然后您可以加入原始查询以仅获取具有最新日期的那些。

(你没有指定表模式,所以我不得不猜测列的名称,但我希望你有这个想法)。


0
投票

使用Row_Number()查找租户的最新记录

  Select * from (
    Select *,Row_number() over(Partition by Tenants order by expirationdate desc) as rn from tablea
    ) x 
    Where rn = 1
© www.soinside.com 2019 - 2024. All rights reserved.