Conditional Max in SQL

I need to execute the following query in 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

Bu this gives me an error:

Cannot perform an aggregate function on an expression
containing an aggregate or a subquery.

The input view is as follows:

EmployeeID    TotaSales MonthNumber
  1             4000      1
  1             6000      2
  2             8500      1
  2             6081      2 

Required Conclusion:

EmployeeID    TotalSale     RecentMonthSale
  1            10000            6000
  2            14581            6081
  3            11458            1012 

I need the next column in my release. EmployeeID, TotalQuantity TotalSale RecentMonthSaleMy view has the next column EmployeeID TotalSale,TotalQuantity, MonthNumber.

+3
source share
2 answers

This query will show the result you need and will scan the table only once.

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
+2
source
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

If you just run each of the subqueries and look at their results, you should get an idea of ​​how this works.

0
source

All Articles