根据地区,获取最大客户及其总销售额(按百分比)

时间:2018-07-27 01:13:22

标签: sql-server adventureworks

使用Adventureworks数据库。

我受困于该地区的前5名客户。如何获得给定格式的输出?

 SELECT TOP 5 CustomerID
    ,oh.TerritoryID
    ,Name
    ,SUM(TotalDue) / (
        SELECT SUM(TotalDue)
        FROM Sales.SalesOrderHeader
        ) * 100 AS [%_of_TotalSale]
FROM Sales.SalesOrderHeader oh
INNER JOIN Sales.SalesTerritory st ON st.TerritoryID = oh.TerritoryID
GROUP BY oh.TerritoryID
    ,CustomerID
    ,Name
ORDER BY [%_of_TotalSale] DESC;

我的输出

My output

输出应如下所示

The output should look like this

1 个答案:

答案 0 :(得分:1)

您的查询存在一些问题。您需要计算每个地区的总数-而非总数。

注意,下面的代码可以分隔为单独的语句。另外,此任务还有其他解决方案。

WITH DataSource AS
(
    SELECT DISTINCT TerritoryID
                    ,CustomerID
                    ,SUM(TotalDue) OVER (PARTITION BY TerritoryID,CustomerID) * 100 / SUM(TotalDue) OVER (PARTITION BY TerritoryID) AS [%_of_TotalSale]
    FROM Sales.SalesOrderHeader
), DataSourceUsersRanked AS
(
    SELECT *
          ,ROW_NUMBER() OVER (PARTITION BY TerritoryID ORDER BY [%_of_TotalSale] DESC) AS RN
    FROM DataSource
), DataSourceUsersFiletred AS
(
    SELECT *
    FROM DataSourceUsersRanked
    WHERE RN <= 5
)
SELECT DSF.TerritoryID
      ,st.[Name]
      ,SUM([%_of_TotalSale]) AS [%_of_TotalSale]
      ,MAX(UserIDs) AS [Top5Customers]
FROM DataSourceUsersFiletred DSF
INNER JOIN Sales.SalesTerritory st
    ON DSF.TerritoryID = st.TerritoryID
CROSS APPLY
(
    SELECT STUFF
    (
        (
            SELECT ',' + CAST(CustomerID AS VARCHAR(12))
            FROM DataSourceUsersFiletred DS1
            WHERE DS1.[TerritoryID] = DSF.[TerritoryID]
            ORDER BY CustomerID
            FOR XML PATH(''), TYPE          
        ).value('.', 'VARCHAR(MAX)')
        ,1
        ,1
        ,''
    )
) Users(UserIDs)
GROUP BY DSF.TerritoryID
        ,st.[Name]
ORDER BY TerritoryID;

enter image description here