我试图获得每年最高的月度销售额。
到目前为止,我的第一年的月销量仅次于第二。
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;
我需要每年第二高。
假设您在newtable中有正确的数据,请关注有关您想要的第二个查询。这是纯SQL:
测试数据:
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
输出:
year secondhighestsale
2010 500
2011 800
2012 500
或者,您可以使用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