我必须在 SQL Server 中执行以下查询:
SELECT EmployeeID,
TotalQuantity AS TotalQty,
TotalSales,
MAX(CASE WHEN MonthNumber = MAX(MonthNumber)
THEN TotalSales END) as RecentMonthSale
FROM vwSales
GROUP BY EmployeeID, TotalQuantity , TotalSales
但是它给了我错误:
输入 View 如下:
EmployeeID TotaSales MonthNumber
1 4000 1
1 6000 2
2 8500 1
2 6081 2
期望的输出:
EmployeeID TotalSale RecentMonthSale
1 10000 6000
2 14581 6081
3 11458 1012
我想在我的输出
EmployeeID, TotalQuantity TotalSale RecentMonthSale
我的 View 中有以下列 EmployeeID TotalSale,TotalQuantity, MonthNumber
。 最佳答案
此查询将显示您需要的输出,并且只会扫描表一次。
select EmployeeID, sum(TotalSales), sum(case when MaxMonth = 1 then TotalSales else 0 end) RecentMonthSales
from
(
select *, rank() over(order by MonthNumber desc) MaxMonth
from
(
select EmployeeID, MonthNumber, sum(TotalSales) TotalSales
from vwSales
group by EmployeeID, MonthNumber
) tt
) tt
group by EmployeeID
关于sql - SQL中的条件最大值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6393989/