SQL为每个部门选择最大销售额的日期[重复]
Posted
技术标签:
【中文标题】SQL为每个部门选择最大销售额的日期[重复]【英文标题】:SQL Selecting dates with maximum sale for each department [duplicate] 【发布时间】:2020-03-06 21:52:36 【问题描述】:我为编写一个棘手的查询而烦恼。
我有下表:
每个部门我想打印利润最大的日期;
我尝试自己提出这样的查询:
Select DISTINCT(Name), Date_sale, MAX(A) as B FROM (SELECT
Departments.Name, SALES.Date_sale, SUM(GOODS.Price * SALES.Quantity)
AS A FROM DEPARTMENTS, GOODS, SALES
WHERE DEPARTMENTS.Dept_id = GOODS.Dept_id AND GOODS.Good_id =
SALES.Good_id GROUP BY DEPARTMENTs.Name, SALES.Date_sale)
GROUP BY Name, Date_sale;
但问题是部门被打印多次,因为我按名称和日期分组。
我应该如何解决它?
【问题讨论】:
【参考方案1】:你可以试试下面的方法-
with cte as
(
SELECT
Departments.Name, SALES.Date_sale, SUM(GOODS.Price * SALES.Quantity)
AS profit FROM DEPARTMENTS inner join GOODS on DEPARTMENTS.Dept_id = GOODS.Dept_id
inner join SALES on GOODS.Good_id = SALES.Good_id
GROUP BY DEPARTMENTs.Name, SALES.Date_sale
)A
select * from cte a
where profit =
(select max(profit) from cte b on a.department=b.department)
或者你可以使用row_number()
select * from
(
select *, row_number() over(partition by department oder by profit desc) as rn
from cte
)A where rn=1
【讨论】:
【参考方案2】:我会在这里使用 join-s,因为它需要从通过第三个表链接的 2 个表中提取信息。
类似这样的东西(但我没有测试过这个查询,只是提出一种方法):
Select department.name as dept, MAX(sales.quantity) as max_sales, sales.date_sale
from goods
Left outer join departments on departments.dept_id = goods.dept_id
Left outer join sales on sales.good_id = goods.good_id
Group by dept
【讨论】:
这在GROUP BY
子句和聚合函数中都不能作为date_sale
工作。【参考方案3】:
您可以使用ROW_NUMBER
编写它,这将为按部门分组的每个日期的总计数提供一个数字,然后您可以使用rn = 1
获取最高销售日期
SELECT NAME, DATE_SALE, A
FROM
(
SELECT
DEPARTMENTS.NAME, SALES.DATE_SALE,
ROW_NUMBER() OVER(
PARTITION BY DEPARTMENTS.NAME
ORDER BY SUM(GOODS.PRICE * SALES.QUANTITY) DESC NULLS LAST
) AS RN,
SUM(GOODS.PRICE * SALES.QUANTITY) AS A
FROM DEPARTMENTS
JOIN GOODS ON ( DEPARTMENTS.DEPT_ID = GOODS.DEPT_ID )
JOIN SALES ON ( GOODS.GOOD_ID = SALES.GOOD_ID )
GROUP BY DEPARTMENTS.NAME,
SALES.DATE_SALE
)
WHERE RN = 1;
重要,使用标准的 ANSI 连接。
干杯!!
【讨论】:
以上是关于SQL为每个部门选择最大销售额的日期[重复]的主要内容,如果未能解决你的问题,请参考以下文章
如何创建查询以显示本周 sql 的每个日期的总销售额 [关闭]
如何用sql的日期函数,分别查出1月~12月每个月的销售金额?