如何获得每年第二高的月度销售额

时间:2019-04-12 03:19:55

标签: sql-server

我正在努力使每年的月销售额排第二位。

到目前为止,我只获得了第一年第二高的月销售额。

WITH newtable AS
(
    SELECT 
    MONTH(o.orderdate) AS 'MONTH',
    YEAR(o.orderdate) AS 'YEAR',
    SUM(od.qty*od.unitprice) AS monthSales
    FROM Sales.Orders AS o
    INNER JOIN Sales.OrderDetails AS od
    ON o.orderid = od.orderid
    GROUP BY YEAR(o.orderdate), MONTH(o.orderdate) 
)
SELECT YEAR, MAX(monthSales) AS secondHighestMonthlySales
FROM newtable
WHERE monthSales < (SELECT MAX(monthSales) FROM newtable)
GROUP BY YEAR;

我每年需要第二高的人。

2 个答案:

答案 0 :(得分:1)

假设您在newtable中有正确的数据,请集中在有关所需内容的第二个查询上。这是纯SQL:

测试数据:

lbl2.setContentHuggingPriority(.defaultHigh, for: .horizontal)

查询以选择倒数第二个:

Year    Sales
2010    500
2010    400
2010    600
2011    700
2011    800
2011    900
2012    400
2012    600
2012    500

输出:

select O.year, max(O.sales) as secondhighestsale from Orders O,
(select year, max(sales) as maxsale
from Orders
group by year) A
where O. year = A.year
and O.sales < A.maxsale
group by O.year

答案 1 :(得分:0)

或者,您可以使用ROWNUMBER()函数。在这种情况下,我使用公用表表达式。我们发现每年的总销售额排名第二。这些年就是所谓的分区。

USE TEMPDB

CREATE TABLE #Sales (SalesYear INT, TotalAmount INT)
INSERT INTO #Sales VALUES (2016, 1100), (2016, 700), (2016, 950),
                          (2017, 660), (2017, 760), (2017, 460),
                          (2017, 141), (2018, 999), (2018, 499);

WITH CTE AS 

(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY SalesYear ORDER BY TotalAmount DESC) AS RowNumb 
    FROM #Sales
)

SELECT SalesYear,
      TotalAmount
FROM CTE WHERE RowNumb = 2