0

我正在尝试编写一个查询来返回总体排名和每组排名。我可以得到“综合排名”,但领土排名不正确。

SELECT        Territory, [Agent Number], [Agent Name], [Commission Level], [Profile End Date], [Prior Year Sales], [Current Year Sales YTD], [Total Sales], Rank() 
                             OVER (PARTITION BY Territory
    ORDER BY [Total Sales]) AS [Territory Rank], Rank() OVER (ORDER BY [Total Sales] DESC) AS [Overall Rank]
    FROM            (SELECT        TerritoryBase.Name AS Territory, ContactExtensionBase.ipl_AgentNumber AS [Agent Number], ContactBase.FullName AS [Agent Name], 
                                                        ContactExtensionBase.ath_activecommissionlevel AS [Commission Level], ContactExtensionBase.ath_profileenddate AS [Profile End Date], 
                                                        CASE WHEN ath_PriorYearSales IS NULL THEN '0' ELSE ath_PriorYearSales END AS [Prior Year Sales], CASE WHEN ath_SalesYTD IS NULL 
                                                        THEN '0' ELSE ath_SalesYTD END AS [Current Year Sales YTD], CASE WHEN ath_PriorYearSales IS NULL 
                                                        THEN '0' ELSE ath_PriorYearSales END + CASE WHEN ath_SalesYTD IS NULL THEN '0' ELSE ath_SalesYTD END AS [Total Sales]
                              FROM            ContactBase INNER JOIN
                                                        ContactExtensionBase ON ContactBase.ContactId = ContactExtensionBase.ContactId INNER JOIN
                                                        TerritoryBase ON ContactExtensionBase.ipl_TerritoryId = TerritoryBase.TerritoryId
                              WHERE        (NOT (ContactExtensionBase.ath_PriorYearSales IS NULL)) AND (ContactExtensionBase.ath_PriorYearSales <> 0) OR
                                                        (NOT (ContactExtensionBase.ath_PriorYearSales IS NULL)) AND (ContactExtensionBase.ath_SalesYTD <> 0) OR
                                                        (ContactExtensionBase.ath_PriorYearSales <> 0) AND (NOT (ContactExtensionBase.ath_SalesYTD IS NULL)) OR
                                                        (NOT (ContactExtensionBase.ath_SalesYTD IS NULL)) AND (ContactExtensionBase.ath_SalesYTD <> 0)) AS DerivedTable1
    ORDER BY [Overall Rank]

以下是上述查询的示例结果: 示例查询结果

我知道我不明白如何使用 Rank。有人可以帮我解决这个问题吗?

编辑:我试图包括马克建议的内容,所以我的等级陈述现在看起来像这样:

SELECT        Territory, [Agent Number], [Agent Name], [Commission Level], [Profile End Date], [Prior Year Sales], [Current Year Sales YTD], [Total Sales], Rank() 
                         OVER (PARTITION BY [Territory]
ORDER BY [Total Sales] Desc) AS [Territory Rank], Rank() OVER (ORDER BY [Total Sales] Desc) AS [Overall Rank]

产生这个:在此处输入图像描述

这已经接近了,但领土排名似乎仍然没有按预期工作。我不确定 8 号和 9 号或 12 到 14 号在领土排名中的位置。我错过了 Rank 的工作原理吗?

4

1 回答 1

1

看起来你是在没有的情况下Territory Rank订购的,所以它可能是倒退的。Total SalesDESCENDING

看看杰克和杰瑞。它们是“地区排名”352 和 353,而不是 1 和 2。

注意:根据你在做什么,考虑你想如何处理平局并注意还有DENSE_RANK,如果有平局,它不会跳过数字。

于 2013-08-30T15:43:18.567 回答