SQL-按国家/地区划分的每月总收入的最大值

SQL-按国家/地区划分的每月总收入的最大值,sql,max,Sql,Max,我正在努力寻找每个国家每个月创纪录的收入。下面的查询为我提供了每个国家每月的收入 select d.calendar_year_month as 'Record_month', c.country_name as 'country' ,sum(Net_qty*(unit_charge+unit_shipping_charge)) as 'Revenue' from sensu_reporting.commercial_analysts.customer_science_transactions

我正在努力寻找每个国家每个月创纪录的收入。下面的查询为我提供了每个国家每月的收入

select d.calendar_year_month as 'Record_month',
c.country_name as 'country'
,sum(Net_qty*(unit_charge+unit_shipping_charge)) as 'Revenue'

from sensu_reporting.commercial_analysts.customer_science_transactions CST (nolock)
join Sensu.dbo.Country_D C (nolock) on cst.country_code = c.Country_Code
join sensu.dbo.Date_D d (nolock) on cst.Order_Date_Key = d.Date_Key


where cst.site_key in ('95')
and cst.order_date_key >= 20180101

group by d.calendar_year_month, c.country_name
我尝试使用:

select a.country,
a.record_month,
max(a.revenue) as 'Record_Revenue'

from(
select d.calendar_year_month as 'Record_month',
c.country_name as 'country'
,sum(Net_qty*(unit_charge+unit_shipping_charge)) as 'Revenue'

from sensu_reporting.commercial_analysts.customer_science_transactions CST (nolock)
join Sensu.dbo.Country_D C (nolock) on cst.country_code = c.Country_Code
join sensu.dbo.Date_D d (nolock) on cst.Order_Date_Key = d.Date_Key


where cst.site_key in ('95')
and cst.order_date_key >= 20180101

group by d.calendar_year_month, c.country_name)
a 
group by country, record_month

但是,这为我提供了与初始查询相同的数据。我做错了什么?我如何修改我的查询,使其只给出每个国家收入最高的月份?

因为我不知道您的表结构,这是一个只有一个表(id、日历年、月、国家代码、收入)的简化示例。我使用子查询来确定最大收入

select calendar_year_month, country, revenue
from reporting r
where revenue = (select max(revenue) from reporting r2 where r.country = r2.country )
group by calendar_year_month, country
我得到的结果是这样的

201802第1500号
201802 SE 3000
201803 DE 7000
201803第1500号

请注意,编号有两行。 我希望这可以转换为您的表结构。

这是您想要的吗

with r as (
      select d.calendar_year_month as Record_month,
             c.country_name as country,
             sum(Net_qty*(unit_charge+unit_shipping_charge)) as Revenue
      from sensu_reporting.commercial_analysts.customer_science_transactions CST join
           Sensu.dbo.Country_D C
           on cst.country_code = c.Country_Code join
           sensu.dbo.Date_D d
           on cst.Order_Date_Key = d.Date_Key
       where cst.site_key in ('95') and cst.order_date_key >= 20180101
       group by d.calendar_year_month, c.country_name
      )
select r.*
from (select r.*,
             row_number() over (partition by record_month order by revenue desc) as seqnum
      from r
     ) r
where seqnum = 1;