有平均值

时间:2016-02-11 19:58:48

标签: sql-server tsql

我正在尝试结合平均值,但这给了我一个错误

select
count(orderId) order,
sum(amount) amountSum
from orders
group by productId
having sum(Amount > avg(sum(Amount))

我可以关闭

中的所有内容
select * from (...) 
outer where outer.amountSum >  

这里复制所有查询但计算avg,有更好的方法吗?

1 个答案:

答案 0 :(得分:3)

;WITH order_stats AS ( 
    SELECT
        productId,
        order_count=COUNT(orderId),
        total=SUM(amount)
    FROM
        orders
    GROUP BY
        productId
)
SELECT
    *
FROM
    order_stats
WHERE
    total>(SELECT AVG(total) FROM order_stats);