如何解决SQL中的条件最大值
| 我必须在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
但是它给了我错误:
Cannot perform an aggregate function on an expression
containing an aggregate or a subquery.
输入视图如下:
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
中跟随以下列。我的视图在the5ѭ中具有下面的列。
解决方法
此查询将显示所需的输出,并且仅扫描表一次。
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
, SELECT
vw.EmployeeID,SUM(vw.TotalSale) as Total,Recent.RecentMonthSale
FROM
vwSales vw
LEFT JOIN
(
SELECT
_vw.EmployeeID,_vw.TotalSale as RecentMonthSale
FROM
vwSales _vw
INNER JOIN
(
SELECT EmployeeID,MAX(MonthNumber) as MaxMonth
FROM vwSales
GROUP BY EmployeeID
) _a
on _vw.EmployeeID = _a.EmployeeID
and _vw.MonthNumber = _a.MaxMonth
) Recent
on Recent.EmployeeID = vw.EmployeeID
GROUP BY
vw.EmployeeID,Recent.RecentMonthSale
如果仅执行每个子查询并查看其结果,则应该对它的工作原理有所了解
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。