SQL视图,分组+内连接同一张表
Posted
技术标签:
【中文标题】SQL视图,分组+内连接同一张表【英文标题】:SQL views, Groupping + inner join the same table 【发布时间】:2018-03-26 22:04:56 【问题描述】:This is my table:
使用此查询,我得到了最畅销的商品:
SELECT [Purchased Item], SUM([Overall Quantity purchased] )
FROM ReportDraft
GROUP BY [Purchased Item]
ORDER BY SUM([Overall Quantity purchased] )
这将返回客户购买的商品和总数量。
如何创建这样的表格
ItemName | Total quantity purchased | Customer who purchased most | Customer quantity bought
Pie--------|---------6------------|---------------Tonya----------|--------4------------|
Big Burger-|---------3------------|---------------Tonya----------|--------3------------| and etc
谢谢
【问题讨论】:
你left join
和group by
【参考方案1】:
为什么你发布一个新问题而不是通知/扩展previous one?
WITH cte AS
(
SELECT [Purchased Item],
-- quantity per item
SUM(SUM([Overall Quantity purchased]))
OVER (PARTITION BY [Purchased Item]) AS "Total quantity purchased",
[Customer name],
-- quantity per item/customer
SUM([Overall Quantity purchased]) AS customer_qantity,
-- rank the customer quantity per item
ROW_NUMBER()
OVER (PARTITION BY [Purchased Item]
ORDER BY SUM([Overall Quantity purchased]) DESC) AS rn
FROM ReportDraft
GROUP BY [Purchased Item], [Customer name]
)
SELECT *
FROM cte
WHERE rn = 1
ORDER BY "Total quantity purchased" DESC
【讨论】:
对此我深表歉意。你的代码工作得很好。您能否推荐一些书来阅读以更清楚地理解数据库,例如这些线背后发生了什么...... @Escaper:我在 30 多年前读过一本数据库初学者的书,所以我真的不能推荐一本 :-) 我通常喜欢 Head First 系列,我喜欢我女儿的数据库漫画指南(她很喜欢)。但是由于您的语法看起来像 MS SQL Server,因此很容易推荐 Itzik Ben-Gan 的书籍,它们涵盖了非常高级的入门。以上是关于SQL视图,分组+内连接同一张表的主要内容,如果未能解决你的问题,请参考以下文章