SQL查询:查找客户的最高收入月/年

时间:2013-10-11 00:29:21

标签: sql database sql-server-2008-r2

我正在查询数据库,以找到系统中所有客户的最高收入月份。我的查询工作是为了从客户数据存在的所有年份中获取每月收入。但是我很难弄清楚如何从这些数据中获得最高的收入。

数据库是SQL Server 2008 R2。 列为:客户名称,年份,月份和收入。 我甚至尝试使用Row_Number()并尝试按客户名称/年分区并按收入排序。但它没有用。也许我在那里犯了一些错误。

以下是我尝试构建基本查询的方法。

Select Customer, Year(orderdatetime) as Year, Month(orderdatetime) as Month, SUM(Revenue)
From Orders
Group By Customer, Year(orderdatetime), Month(orderdatetime)

这就是我尝试使用Row_Number()

的方法
WITH Max_Revenue AS
(
Select Customer, Year(orderdatetime) as Year, Month(orderdatetime) as Month, SUM(Revenue), RowNumber = ROW_NUMBER() OVER(PARTITION By Year Order By Revenue DESC)
    From Orders
    Group By Customer, Year(orderdatetime), Month(orderdatetime)
)
Select Max_Revenue.Customer, Max_Revenue.Year, Max_Revenue.Month, Max_Revenue.Revenue
From Max_Revenue
Where Max_Revenue.RowNumber = 1
Order By Max_Revenue.Customer asc

我得到的数据如下:

Customer   Month   Year  Revenue
  ABC        2       2012  100
  ABC        3       2013  150
  ABC        5       2012  200
  XYZ        4       2011  500
  XYZ        6       2012  650
  XYZ        7       2012  800

我想要的输出是什么

 Customer   Month   Year  Revenue
 ABC        5       2012  200
 XYZ        7       2012  800

因此,每个客户的最佳月份和各年的收入。

1 个答案:

答案 0 :(得分:1)

 SELECT Customer,
        Year,
        Revenue,
        Month  
 FROM (
       SELECT Customer,
              Year,
              ROW_NUMBER() OVER(PARTITION By Customer Order By Revenue DESC) as rank,
              Revenue,
              Month

       FROM (
              Select Customer, 
                     Year(orderdatetime) as Year, 
                     Month(orderdatetime) as Month, 
                     SUM(Revenue) as Revenue
              From   Orders 
              Group By 
                    Customer, 
                    Year(orderdatetime), 
                    Month(orderdatetime)
              ) BS

    GROUP BY Customer,
             Year,
             Month) BS2    
WHERE BS2.rank = 1

OR change = ROW_NUMBER()OVER(按年份划分按收入DESC到             = ROW_NUMBER()OVER(按收入DESC划分客户订单