很抱歉,如果之前有人询问过,但我无法找到解决方案或在任何地方找到任何内容。
基本上我需要做的是只为连接显示超过300的金额,这会从具有匹配ID的注册中累计总金额
在更简单的表术语中,表A和表B. 我需要通过加入WHERE A.ID和B.ID匹配并总结B.Amount来获得B.Amount总数,其中B.ID是重复的。 这就是我过去通过B.ID分组付款来支付的注册总数:
SELECT tblattendees.FirstName, tblattendees.LastName,
SUM(tblregistration.RegistrationPaid) AS 'TotalPaid'
FROM tblattendees
JOIN tblregistration
ON tblregistration.RegistrationID = tblattendees.AttendeeID
GROUP BY tblregistration.AttendeeID
这样可以正常工作,直到您想要将结果限制在300以上
我尝试在连接之后添加WHERE并使用AND和ON,但是由于我使用GROUP BY来获得总共RegistrationsPaid,所以它似乎很混乱。
也许有些事我不理解,任何帮助都会非常感激。
答案 0 :(得分:1)
您可以在WHERE
子句中使用子查询和使用条件:
SELECT *
FROM (
SELECT tblattendees.FirstName, tblattendees.LastName,
SUM(tblregistration.RegistrationPaid) AS `TotalPaid`
FROM tblattendees
JOIN tblregistration
ON tblregistration.RegistrationID = tblattendees.AttendeeID
GROUP BY tblregistration.AttendeeID
) AS sub
WHERE sub.TotalPaid > 300
或者您可以使用评论中提出的HAVING
:
SELECT tblattendees.FirstName, tblattendees.LastName,
SUM(tblregistration.RegistrationPaid) AS `TotalPaid`
FROM tblattendees
JOIN tblregistration
ON tblregistration.RegistrationID = tblattendees.AttendeeID
GROUP BY tblregistration.AttendeeID
HAVING SUM(tblregistration.RegistrationPaid) > 300
在MySQL
中,您应该直接使用别名:
SELECT tblattendees.FirstName, tblattendees.LastName,
SUM(tblregistration.RegistrationPaid) AS `TotalPaid`
FROM tblattendees
JOIN tblregistration
ON tblregistration.RegistrationID = tblattendees.AttendeeID
GROUP BY tblregistration.AttendeeID
HAVING `TotalPaid` > 300;