如何识别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行的预期结果,每三行有一个城市,它的销售量最高,也是哪个类别的销售量最高的。
答案 0 :(得分:1)
尝试一下:
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;