首页 > 解决方案 > 这个问题的正确查询是什么?

问题描述

如何识别 3 个最重要(收入最高)的城市,并针对这些城市显示 3 个顶级类别的细分。

我在 Adventureworkslt2014 上工作。

这是我的查询,但我从同一个城市获得了最好的三个销售:

select top 3 sum(TotalDue) as bestrevenue,city,pc.Name 
from SalesLT.ProductCategory as pc
join SalesLT.Product p 
on pc.ProductCategoryID =p.ProductCategoryID
join SalesLT.SalesOrderDetail as sod
on sod.ProductID=p.ProductID 
join SalesLT.SalesOrderHeader as soh 
on soh.SalesOrderID = soh.SalesOrderID
join SalesLT.[Address] addr
on addr.AddressID = soh.BillToAddressID
group by city,pc.Name
order by bestrevenue desc`

预期结果我应该得到 9 行,每三行有同一个城市,它的销售额最高,也来自哪个类别的销售额最高。

标签: sqlsql-serveradventureworks

解决方案


尝试这个:

select t.*
from(select city, pc.Name, sum(TotalDue) as bestrevenue,
            row_number() OVER(partition by city,Name ORDER BY sum(TotalDue) desc) as RN 
     from SalesLT.ProductCategory as pc join 
          SalesLT.Product p 
          on pc.ProductCategoryID =p.ProductCategoryID join 
          SalesLT.SalesOrderDetail as sod
          on sod.ProductID=p.ProductID join 
          SalesLT.SalesOrderHeader as soh 
          on soh.SalesOrderID = soh.SalesOrderID join 
          SalesLT.[Address] addr
          on addr.AddressID = soh.BillToAddressID
     group by city,pc.Name
    ) t
where RN <= 3;

推荐阅读