2014-02-12 119 views
1

這是我的查詢在更新語句TSQL聚合函數

UPDATE [P1_Log_FY14H1_CE] 
    SET [P1_Log_FY14H1_CE].toplevelAccredCode = #PartnerLookupfinalForCode.Accreditation_Code 
    FROM dbo.[P1_Log_FY14H1_CE] 
    INNER JOIN #PartnerLookupfinalForCode 
    ON [P1_Log_FY14H1_CE].[Partner ID] = #PartnerLookupfinalforCode.Partner_ID 
    WHERE [P1_Log_FY14H1_CE].Intake_Date is not null and #PartnerLookupfinalforCode.[Rank]=(Select Min(Rank) from #PartnerLookupfinalforCode) 

這裏當updateing Toplevelaccredcode

我爲得到結果這樣

[Partner ID] Code  Rank 
A    silver 3 
A    LessSilver 4 

在這裏記錄表方A具有獨特的記錄。我想在日誌表中更新最高。 贊同合作伙伴銀應該更新。 任何人都可以糾正我的查詢嗎?

回答

0

試試這個:

WITH c AS (
    SELECT Partner_ID 
    , Accreditation_Code 
    , RANK() OVER(PARTITION BY Partner_ID ORDER BY [Rank]) [min_rank] 
    FROM #PartnerLookupfinalForCode) 

UPDATE [P1_Log_FY14H1_CE] 
SET [P1_Log_FY14H1_CE].toplevelAccredCode = c.Accreditation_Code 
FROM dbo.[P1_Log_FY14H1_CE] 
INNER JOIN c ON [P1_Log_FY14H1_CE].[Partner ID] = c.Partner_ID 
    AND c.min_rank = 1 
WHERE [P1_Log_FY14H1_CE].Intake_Date is not null 
0

試試這個

UPDATE [P1_Log_FY14H1_CE] 
    SET [P1_Log_FY14H1_CE].toplevelAccredCode = #PartnerLookupfinalForCode.Accreditation_Code 
    FROM dbo.[P1_Log_FY14H1_CE] 
    INNER JOIN #PartnerLookupfinalForCode 
    ON [P1_Log_FY14H1_CE].[Partner ID] = #PartnerLookupfinalforCode.Partner_ID 
    INNER JOIN (Select Partner_ID,Code,Min(Rank) from #PartnerLookupfinalforCode Group By Partner_ID,Code) MINPartner 
    ON MINPartner.Partner_ID =#PartnerLookupfinalforCode.Partner_ID AND MINPartner.Code=#PartnerLookupfinalforCode.Code 
    WHERE [P1_Log_FY14H1_CE].Intake_Date is not null