目标:
尝试:
SELECT alumni.alumni_id, alumni.alumni_name,
(SELECT SUM(contributed_amt) FROM contribution WHERE contribution.alumni_id = alumni.alumni_id) AS contrib_alltime_total,
(SELECT SUM(contributed_amt) FROM contribution WHERE contribution.alumni_id = alumni.alumni_id AND contribution.date >= 2002-10-10 AND contribution.date <= 2003-10-10) AS contrib_range_total
FROM alumni
WHERE hold_code IS NULL
ORDER BY lname ASC
HAVING contrib_range_total >= 2000
HAVING contrib_range_total <= 3000
我收到语法错误,很可能是因为我试图使用两个HAVING的
我也意识到你想使用带有GROUP BY的HAVING,但我不需要进行任何分组
我可能会这样做,但我认为它效率低,可能需要很长时间
SELECT alumni.alumni_id, alumni.alumni_name,
(SELECT SUM(contributed_amt) FROM contribution WHERE contribution.alumni_id = alumni.alumni_id) AS contrib_alltime_total,
(SELECT SUM(contributed_amt) FROM contribution WHERE contribution.alumni_id = alumni.alumni_id AND contribution.date >= 2002-10-10 AND contribution.date <= 2003-10-10) AS contrib_range_total
FROM alumni
WHERE hold_code IS NULL
AND (SELECT SUM(contributed_amt) FROM contribution WHERE contribution.alumni_id = alumni.alumni_id AND contribution.date >= 2002-10-10 AND contribution.date <= 2003-10-10) >= 2000
AND (SELECT SUM(contributed_amt) FROM contribution WHERE contribution.alumni_id = alumni.alumni_id AND contribution.date >= 2002-10-10 AND contribution.date <= 2003-10-10) <= 3000
ORDER BY lname ASC
实现这一目标的最快,最有效的方法是什么?欢迎任何建议,谢谢你的时间
答案 0 :(得分:0)
SELECT a.alumni_id, a.alumni_name,
SUM(c.contributed_amt) AS contrib_alltime_total,
SUM(c.contributed_amt) AS contrib_range_total
FROM alumni a, contribution c
WHERE a.hold_code IS NULL
AND c.alumni_id = a.alumni_id AND c.date BETWEEN '2002-10-10' AND '2003-10-10'
AND contrib_range_total BETWEEN 2000 AND 3000
ORDER BY lname ASC
答案 1 :(得分:0)
我认为,如果没有HAVING
,您就无法使用GROUP BY
,并使用AND
加入多个HAVING
个案例......
GROUP BY contrib_range_total HAVING contrib_range_total >= 2000 AND contrib_range_total <= 3000
答案 2 :(得分:0)
SELECT a.alumni_id,
sum(c.contributed_amt) AS contrib_alltime_total,
sum(case when c.contribution_date BETWEEN '2002-10-10' AND '2003-10-10' then c.contributed_amt else 0 end) AS contrib_range_total
FROM alumni a
INNER JOIN contribution c ON c.alumni_id = a.alumni_id
WHERE a.hold_code IS NULL
GROUP BY a.alumni_id
HAVING contrib_range_total BETWEEN 2000 AND 3000