sql - 这个问题的正确查询是什么?
问题描述
如何识别 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 行,每三行有同一个城市,它的销售额最高,也来自哪个类别的销售额最高。
解决方案
尝试这个:
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;
推荐阅读
- java - 使用循环从 int 值打印字符,每行输出所需的数字数量
- c++ - C++ 中的链表数据结构错误
- xgboost - 在 AWS Sagemaker 上安装 graphiz
- matlab - 难以将我的所有 6 个 matlab 图形打印到 PDF(Matlab)
- jquery - 通过悬停 ElementA 和 ElementB 更改 elementA
- android - qemu-system-aarch64:加载状态时出错,例如设备“goldfish_pipe”的 0x0
- ubuntu - 如何将 glibc 作为静态库?
- amazon-web-services - 如何在无服务器和 webpack 的 lambda 函数构建中使用特定版本的 aws-sdk?
- javascript - 在 javascript 中构建查询字符串并将参数合并到一个参数中
- c - C 编程中的链表