编写一个 SQL 查询来判断过去 6 个月中按国家/地区分组的最大销售额是一年中的哪一周?

Posted

技术标签:

【中文标题】编写一个 SQL 查询来判断过去 6 个月中按国家/地区分组的最大销售额是一年中的哪一周?【英文标题】:Write a SQL query to tell which week of the year had the max number of sales grouped by country for last 6 months? 【发布时间】:2021-12-23 16:50:36 【问题描述】:

我正在尝试编写一个查询,该查询将返回过去 6 个月中每个国家/地区的销售额最大的一周。 到目前为止我试过了

select country_id, datepart(week, order_date) as weekofyear, count(order_id) from order_table group by country_id,weekofyear having count(order_id) = (select count(order_id) as c from order_table group by country_id order by c limit 1);

请帮忙。

【问题讨论】:

你如何定义一年中的一周? 使用 datepart 函数获取日历年的周数。例如,2 月 1 日将落在一年的第 5 周。 给定日期不需要每年都在同一周。 【参考方案1】:

创建一个子查询,该查询显示每周的总销售额,然后子查询结果并找到一周的最大销售额。使用 row_number 按 country_id、weekofyear 和降序销售的顺序进行分区。

select *
from
(
select country_id
,weekofyear
,occurrences
,row_number() over(partition by country_id order by country_id,occurrences desc) row_id
from
(

select distinct country_id,datepart(week,order_date) weekofyear, count(order_id) occurrences from orders
where order_date is not null
group by country_id,datepart(week,order_date)
)x
)y
where row_id=1

【讨论】:

首先将国家和星期几与计数分组。得到结果并确认它们是正确的。接下来,对结果进行分区并按每个国家/地区出现次数最多的生成 row_id 排序,然后仅输出排名靠前的结果

以上是关于编写一个 SQL 查询来判断过去 6 个月中按国家/地区分组的最大销售额是一年中的哪一周?的主要内容,如果未能解决你的问题,请参考以下文章

sql题 如何统计查询一个月中每天的记录

如何根据状态编写过滤国家/地区的 sql 查询

SQL 查询中分组 COUNT 的总和

Moment js按星期和星期几获取一个月中的特定日期

SQL:编写查询按性别获取平均订单价值

SQL数字/日期模式分析/时间跨度