我有几个查询结果使用一个或多个聚合函数和一个日期GROUP-BY,所以它们看起来像这样:
Date VisitCount(COUNT) TotalBilling(SUM) 1/1/10 234 15765.21 1/2/10 321 23146.27 1/3/10 289 19436.51
以上简化的SQL是:
SELECT
VisitDate,
COUNT(*) AS VisitCount,
SUM(BilledAmount) AS TotalBilling
FROM Visits
GROUP BY VisitDate
我想要的是一种将聚合函数(如AVG)应用于结果集中的一列的方法。例如,我想在结果集中添加“AvgVisits”和“AvgBilling”列,如下所示:
Date VisitCount(COUNT) TotalBilling(SUM) AvgVisits AvgBilling 1/1/10 234 15765.21 281.3 19449.33 1/2/10 321 23146.27 281.3 19449.33 1/3/10 289 19436.51 281.3 19449.33
SQL不允许将聚合函数应用于另一个聚合函数或子查询,因此我能想到的唯一方法是使用临时表或迭代结果集并手动计算值。有没有办法在没有临时表或手动计算的情况下在MSSQL2008中执行此操作?
答案 0 :(得分:5)
with cteGrouped as (
SELECT
VisitDate,
COUNT(*) AS VisitCount,
SUM(BilledAmount) AS TotalBilling
FROM Visits
GROUP BY VisitDate),
cteTotal as (
SELECT COUNT(*)/COUNT(DISTINCT VisitDate) as AvgVisits,
SUM(BilledAmount)/COUNT(DISTINCT VisitDate) as AvgBilling
FROM Visits)
SELECT *
FROM cteGrouped
CROSS JOIN cteTotal;
您可以通过子查询实现相同的目标,我发现CTE更具表现力。
答案 1 :(得分:1)
类似于
的东西select *,avg(visitcount) over(),
avg(totalbilling) over()
from(
SELECT
VisitDate,
COUNT(*) AS VisitCount,
SUM(BilledAmount) AS TotalBilling
FROM Visits
GROUP BY VisitDate) as a
答案 2 :(得分:0)
如果您特别想避免使用临时表,我相信可以使用Common Table Expression来完成。