如何使用union获取最后一行中特定列的总和

时间:2013-08-14 11:39:01

标签: sql sql-server tsql

我希望得到平均值

SELECT
        Employees.EmployeeID AS EMPLOYEEID,
        Employees.EMPLOYEENAMESURNAMEFORMAT AS LastFirstName,

        SUM(MAILCOUNT) MAILCOUNT,
        COUNT(*) DAYCOUNT,
        AVG(MAILCOUNT) AVERAGE 
    FROM Employees
    LEFT JOIN ST_LAWERP_DAILYMAIL_PERFORMANCE ON Employees.EmployeeID = ST_LAWERP_DAILYMAIL_PERFORMANCE.EMPLOYEEID
    WHERE Employees.ACTIVESTATUS = 1 
        AND Employees.Loginname<>''
        AND Employees.Title NOT IN ('Chauffeur','Intern','Summer Intern')
        AND ST_LAWERP_DAILYMAIL_PERFORMANCE.DATE BETWEEN '2011-01-01' AND '2015-01-01'

    GROUP BY Employees.EmployeeID,Employees.EMPLOYEENAMESURNAMEFORMAT

1 个答案:

答案 0 :(得分:1)

您可以使用窗口函数来获得平均值的总和:

SELECT
        Employees.EmployeeID AS EMPLOYEEID,
        Employees.EMPLOYEENAMESURNAMEFORMAT AS LastFirstName,

        SUM(MAILCOUNT) MAILCOUNT,
        COUNT(*) DAYCOUNT,
        AVG(MAILCOUNT) AVERAGE ,
        sum(avg(MAILCOUNT)) over () as SUMAVERAGE
    FROM Employees
    LEFT JOIN ST_LAWERP_DAILYMAIL_PERFORMANCE ON Employees.EmployeeID = ST_LAWERP_DAILYMAIL_PERFORMANCE.EMPLOYEEID
    WHERE Employees.ACTIVESTATUS = 1 
        AND Employees.Loginname<>''
        AND Employees.Title NOT IN ('Chauffeur','Intern','Summer Intern')
        AND ST_LAWERP_DAILYMAIL_PERFORMANCE.DATE BETWEEN '2011-01-01' AND '2015-01-01'

    GROUP BY Employees.EmployeeID,Employees.EMPLOYEENAMESURNAMEFORMAT