[英]Get the max value of a column
我有以下查詢:
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的行。 可以幫我嗎? 謝謝。
嘗試將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
這應該為您提供所需的結果:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.