仅显示SUM(价格)超过特定数量

时间:2018-03-17 22:33:04

标签: sql postgresql

我有3张桌子:

  • 客户(姓名,身份证),
  • 项目(名称,价格,ID),
  • 购买(id,items_id,customers_id)

当我跑步时:

select 
 customers.name,
 SUM(items.price) as "price"
from items
INNER JOIN purchases
ON items.id = purchases.item_id
INNER JOIN customers
ON purchases.customer_id = customers.id
GROUP BY customers.name
ORDER BY "price"

这是我得到的结果:

"Anne Watson" "5.00"
"Craig Scott" "11.30"
"Michael Adam" "101.29"
"Jose Salvatierra" "899.00"
"Rolf Smith" "1174.50"

但是,我想只显示那些价格超过100的行(在这种情况下为3个底部行)。我怎么能这样做?

3 个答案:

答案 0 :(得分:2)

这是您使用HAVING子句的地方。它与WHERE子句类似,但在GROUP BY之后应用。

HAVING SUM(items.price) > 100

答案 1 :(得分:1)

如果您只想要大于100的SUM(价格)包含如下的HAVING子句。

select 
 customers.name,
 SUM(items.price) as "price"
from items
INNER JOIN purchases
ON items.id = purchases.item_id
INNER JOIN customers
ON purchases.customer_id = customers.id
GROUP BY customers.name
having sum(items.price) >100

答案 2 :(得分:0)

这是WHERE函数的解决方案

select 
   customers.name,
   SUM(items.price) as price
from items, purchases, customers
where 
   items.id = purchases.item_id and purchases.customer_id = customers.id and 
   items.price > 100

GROUP BY customers.name
ORDER BY price;