我有以下查询:
select JdeAddressNo, LicenseNo, ExpirationDate, max(LicenseTypeId) licensetypeid
from Licensing_DEV..License group by JdeAddressNo, LicenseNo, ExpirationDate
此查询返回此结果集:
Address# License# Expire date LicenseTypeID
30155 304157 2 015-08-31 00:00:00.000 2
30155 PB0020052 2014-07-31 00:00:00.000 6
30162 0000000115 2016-01-31 00:00:00.000 2
30162 115 2014-01-31 00:00:00.000 3
30162 PR0205559 2014-04-30 00:00:00.000 6
30171 10CW00029700 2014-09-30 00:00:00.000 3
如您所见,某些地址编号会返回重复的行。我需要的是根据许可证类型ID消除欺骗。我想只返回licensetypeID最高的行。因此,对于地址号30155,只应返回许可证类型ID为6的行。有人可以帮助我吗?谢谢。
答案 0 :(得分:0)
尝试将Row_number()
与Partition by clause
select * from
(
select *,rn=row_number()over(partition by Address# order by LicenseTypeID desc) from table
)x
where x.rn=1
答案 1 :(得分:0)
这可以为您提供所需的结果:
select L1.JdeAddressNo, L1.LicenseNo, L1.ExpirationDate, L1.LicenseTypeId
from Licensing_DEV..License L1
INNER JOIN (SELECT JdeAddressNo, max(LicenseTypeId) as maxlicensetypeid
FROM Licensing_DEV..License
GROUP BY JdeAddressNo
) L2 ON
L1.JdeAddressNo = L2.JdeAddressNo AND
L1.LicenseTypeId = l2.maxlicensetypeid