简体   繁体   English

SQL: select 客户营业额最大的年份和月份怎么办?

[英]SQL: How to select year and month when customer's turnover was the biggest?

I need to List top 10 customers by average monthly transactions amount turnover, in additional column indicating the year and month with highest monthly turnover of the customer.我需要按平均每月交易额营业额列出前 10 名客户,在附加列中显示客户每月营业额最高的年份和月份。

I made the first part - list top 10 customers by average monthly transactions amount turnover.我做了第一部分 - 按平均每月交易额营业额列出前 10 名客户。

Select column1, AVG(Case when when column1="x" then column2
                      when column1="y" then column2
                      when column1="z" then column2
                      when column1="q" then column2 End)/12 [AVG]
from table1
Group by column1
Order by AVG DESC;

How to make the second part of the task - in additional column indicating the year and month with highest monthly turnover of the customer?如何制作任务的第二部分 - 在附加栏中显示客户月营业额最高的年份和月份?

This sounds like aggregation and window functions.这听起来像聚合和 window 函数。 Date functions are notoriously database-dependent, but the idea is:众所周知,日期函数依赖于数据库,但其想法是:

select ymc.*
from (select year(r_date) as yyyy, month(r_date) as mm, c_id, sum(amount) as amount,
             row_number() over (partition by c_id order by sum(amount) desc) as seqnum
      from t
      group by year(r_date), month(r_date), c_id
     ) ymc
where seqnum = 1;

Not all databases support year() and month() but all have similar functionality.并非所有数据库都支持year()month()但都具有相似的功能。 So you may need to modify for what your database uses.因此,您可能需要针对数据库使用的内容进行修改。

Use below query, below query in for Oracle, tag your database so that can provide appropriate query.使用下面的查询,下面的查询为 Oracle,标记您的数据库以便可以提供适当的查询。

select c_id, to_char(r_date, 'MM'), to_char(r_date, 'YYYY'), max(amount)
group by c_id, to_char(r_date, 'MM'), to_char(r_date, 'YYYY');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM