SELECT
EmailOfConsumer,
COUNT(EmailOfConsumer) as 'NumberOfOrders',
SUM(CAST(Total as money)) as 'TotalValue',
(SUM(CAST(Total as money))/COUNT(EmailOfConsumer)) as 'AverageValue'
FROM webshop
GROUP BY EmailOfConsumer
ORDER BY TotalValue DESC
这回来了:
EmailOfConsumer NumberOfOrders TotalValue AverageValue
test 1 2000000000.10 2000000000.10
我想在WHERE NumberOfOrders = '1'
我尝试添加WHERE COUNT(EmailOfConsumer) = '1'
但是我收到了这个错误:
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a
HAVING clause or a select list, and the column being aggregated is an outer reference.
答案 0 :(得分:2)
使用
HAVING COUNT(EmailOfConsumer) = 1
having子句限制聚合,而where子句仅限制单个列数据
答案 1 :(得分:2)
使用group by然后具有子句。请参阅this
SELECT
EmailOfConsumer,
COUNT(EmailOfConsumer) as 'NumberOfOrders',
SUM(CAST(Total as money)) as 'TotalValue',
(SUM(CAST(Total as money))/COUNT(EmailOfConsumer)) as 'AverageValue'
FROM webshop
GROUP BY EmailOfConsumer
HAVING COUNT(EmailOfConsumer) = '1'
ORDER BY TotalValue DESC
答案 2 :(得分:1)
SELECT
EmailOfConsumer,
COUNT(EmailOfConsumer) as 'NumberOfOrders',
SUM(CAST(Total as money)) as 'TotalValue',
(SUM(CAST(Total as money))/COUNT(EmailOfConsumer)) as 'AverageValue'
FROM webshop
GROUP BY EmailOfConsumer
HAVING COUNT(EmailOfConsumer) = '1'
ORDER BY TotalValue DESC
答案 3 :(得分:1)
你可以尝试
SELECT
EmailOfConsumer,
COUNT(EmailOfConsumer) as 'NumberOfOrders',
SUM(CAST(Total as money)) as 'TotalValue',
(SUM(CAST(Total as money))/COUNT(EmailOfConsumer)) as 'AverageValue'
FROM webshop
GROUP BY EmailOfConsumer
HAVING COUNT(EmailOfConsumer) = 1
ORDER BY TotalValue DESC
答案 4 :(得分:1)
您需要在HAVING clause
中添加过滤条件。 COUNT也会返回数值,因此无需添加引号来检查:
SELECT EmailOfConsumer,
COUNT(EmailOfConsumer) as 'NumberOfOrders',
SUM(CAST(Total as money)) as 'TotalValue',
(SUM(CAST(Total as money))/COUNT(EmailOfConsumer)) as 'AverageValue'
FROM webshop
GROUP BY EmailOfConsumer
HAVING COUNT(EmailOfConsumer) = 1
ORDER BY TotalValue DESC
您无法使用COUNT in WHERE clause
检查条件,因为它会在聚合之前执行,因此您需要在HAVING clause
中汇总后进行检查。
答案 5 :(得分:1)
使用此查询:
SELECT
EmailOfConsumer,
COUNT(EmailOfConsumer) as 'NumberOfOrders',
SUM(CAST(Total as money)) as 'TotalValue',
(SUM(CAST(Total as money))/COUNT(EmailOfConsumer)) as 'AverageValue'
FROM webshop
GROUP BY EmailOfConsumer
HAVING COUNT(*) = 1
ORDER BY TotalValue DESC
注意:
WHERE
子句位于 GROUP BY
之前,而HAVING
子句位于 GROUP BY
WHERE
子句在聚合之前过滤行; HAVING
子句过滤聚合行COUNT(...)
会返回一个数字,因此常量1
应该不用引号括起来。