2014-06-16 44 views
0

我有以下查詢:得到一個列的最大值

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

您的問題是,你是拉低了太多列。一旦你創建了一個獨特的記錄(其中,有唯一的列將做),它會創建一個新的MAX值搜索。您可能需要對最大值執行subSELECT,因此您只需抓取它找到的最後一個。 – durbnpoisn

回答

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 
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