gpt4 book ai didi

sql-server - 基于地域,获取顶级客户及其总销售额的百分比

转载 作者:行者123 更新时间:2023-12-04 15:56:14 25 4
gpt4 key购买 nike

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

最佳答案

您的查询有一些问题。您需要计算每个地区的总数 - 而不是全部总数。

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

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

关于sql-server - 基于地域,获取顶级客户及其总销售额的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51549464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com