SQL中的条件最大值

时间:2011-06-18 04:57:46

标签: sql sql-server tsql sql-server-2008 query-optimization

我必须在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我的视图包含以下列EmployeeID TotalSale,TotalQuantity, MonthNumber

2 个答案:

答案 0 :(得分:2)

此查询将显示您需要的输出,并且只扫描一次表。

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

答案 1 :(得分:0)

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

如果您只是执行每个子查询并查看其结果,您应该知道这是如何工作的