2

我正在查询数据库以找到系统中所有客户的最高收入月份。我已经得到了查询,以从存在数据的所有年份中提取客户的月收入。但我正在努力弄清楚如何从这些数据中获得最高的月收入。

数据库是 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

因此,就收入而言,每个客户的最佳月份和相应年份。

4

1 回答 1

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

或更改 = ROW_NUMBER() OVER(PARTITION By Year Order By Revenue DESC to = ROW_NUMBER() OVER(PARTITION By Customer Order By Revenue DESC

于 2013-10-11T00:53:45.590 回答