SQL - 按国家/地区按月收入的最大总和

时间:2018-05-05 19:32:58

标签: 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 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

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

2 个答案:

答案 0 :(得分:0)

由于我不知道你的表结构,这是一个只有一个表(id,calendar_year_month,countrycode,revenue)的简化示例。我使用子查询来确定最大收入。

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 NO 1500
  201802 SE 3000
  201803 DE 7000
  201803 NO 1500

注意NO有两行。 我希望这可以转换为你的表结构。

答案 1 :(得分:0)

这是你想要的吗?

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;