家庭作业的问题是显示具有多个礼物的房屋总数。下面的列表显示了它们是哪些,但我无法解决查询,将它们显示为总共6个。我还是新的并且学习Mysql,我为无知而道歉。
Mysql数据
**address** **Number of presents per home**
2 Bay Road 2
2a Neptune Road 2
45 Bay Road 2
59 Black Street 2
65 Mainway Avenue 3
89 White Street 2
使用的查询:
SELECT address, SUM(goodBehaviour) AS `Number of Houses with Multiple presents`
FROM wishlist
GROUP BY address
HAVING SUM(goodBehaviour) >1;
我已经尝试了一些其他查询来总计地址列但是无法显示我想要的输出。感谢。
答案 0 :(得分:1)
问题在于您对goodBehaviour
字段的值求和,但您应该计算超过1个字段的地址数。
如果每个地址在您的表中只有1条记录(基于您的样本数据):
select count(address)
from wishlist
where goodBehaviour >1
如果您可以为单个地址创建多个记录,那么在子查询中,您需要对礼物数量求和并计算外部查询中的地址数量,其中礼物总数超过1:
select count(address)
from
(select address, sum(goodBehaviour) as presents
from wishlist
group by address) t
where t.presents>1
答案 1 :(得分:0)
如果您需要房屋总数 - 您可以将查询用作子查询:
SELECT count(*) FROM (SELECT address, SUM(goodBehaviour) AS `Number of Houses with Multiple presents`
FROM wishlist
GROUP BY address
HAVING SUM(goodBehaviour) >1) x;