如何以总价格显示每笔交易的客户名称高于平均价格?

时间:2016-12-19 14:14:26

标签: sql subquery average aliasing

如果总价高于每次交易的平均价格,我想显示客户名称。但是错误消息是“列'x.average'在HAVING子句中无效,因为它不包含在聚合函数或GROUP BY子句中。”我不知道问题出在哪里。

这是我的代码

SELECT  c.CustomerId,
        hs.TransactionId,
        c.CustomerName,
        SUM(t.Price) AS [Total Price]
FROM MsCustomer c JOIN HeaderSalonServices hs
ON c.CustomerId = hs.CustomerId
JOIN DetailSalonServices ds
ON ds.TransactionId = hs.TransactionId
JOIN MsTreatment t
ON t.TreatmentId = ds.TreatmentId,
(SELECT AVG(Price) AS average
 FROM MsTreatment) AS x
GROUP BY c.CustomerId, hs.TransactionId, c.CustomerName
HAVING SUM(t.Price) > average

1 个答案:

答案 0 :(得分:1)

尝试将子查询移动到HAVING子句:

SELECT  c.CustomerId,
        hs.TransactionId,
        c.CustomerName,
        SUM(t.Price) AS [Total Price]
FROM MsCustomer c JOIN HeaderSalonServices hs
ON c.CustomerId = hs.CustomerId
JOIN DetailSalonServices ds
ON ds.TransactionId = hs.TransactionId
JOIN MsTreatment t
ON t.TreatmentId = ds.TreatmentId
GROUP BY c.CustomerId, hs.TransactionId, c.CustomerName
HAVING SUM(t.Price) > (SELECT AVG(Price) AS average FROM MsTreatment)