我有一个包含3个字段的数据列表,ISIN,CompanyId和EffectiveDate。 ISIN在CompanyId和生效日期都重复。
示例数据:
SELECT ISIN, CompanyId, MAX(EffectiveDate)
FROM [MappingData].[dbo].[ESGMappingISIN]
GROUP BY ISIN,CompanyId
使用
ISIN CompanyId EffectiveDate
AED001410045 58105545 2012-02-09
AEDFXA1G39P8 132844116 2017-09-21
ARDEUT110020 249603 2012-02-09
ARDEUT110020 416264458 2017-03-22
我可以删除ISIN和CompanyId上的重复项以返回
A) Return ISIN and CompanyId where ISIN is distinct
B) If 1 ISIN has 2 CompanyIds, return the line with the later effective date.
我需要的最后一步是:
ISIN CompanyId EffectiveDate
AED001410045 58105545 2012-02-09
AEDFXA1G39P8 132844116 2017-09-21
ARDEUT110020 416264458 2017-03-22
理想输出
{{1}}
答案 0 :(得分:1)
您可以使用row_number()
:
SELECT *
FROM (SELECT ISIN, CompanyId, MAX(EffectiveDate) as maxed,
ROW_NUMBER() OVER (PARTITION BY ISIN ORDER BY MAX(Effectivedate) DESC) as seqnum
FROM [MappingData].[dbo].[ESGMappingISIN]
GROUP BY ISIN, CompanyId
) m
WHERE seqnum = 1;
答案 1 :(得分:1)
你可以使用这样的子查询:
SELECT
B.ISIN,
B.CompanyID,
B.EffectiveDate
FROM
(
SELECT
ISIN,
CompanyId,
MAX(EffectiveDate) AS EffectiveDate
FROM
ESGMappingISIN
GROUP BY
ISIN,
CompanyId
)
AS B
JOIN
(
SELECT
ISIN,
MAX(EffectiveDate) AS EffectiveDate
FROM
ESGMappingISIN
GROUP BY ISIN
) AS A
ON B.ISIN = A.ISIN
AND B.EffectiveDate = A.EffectiveDate