MySQL Query有两个条件内联SELECT

时间:2010-11-22 06:08:33

标签: mysql

目标:

  • 有两张桌子,一张校友表和一份捐款表 - 每份捐款都与校友的ID有关
  • 获取有校友的名单 在该日期内贡献了2-3000 范围2002-10-10和2003-10-10。
  • 结果需要显示校友的姓名,身份证,每位校友的历史总数,以及每位校友的总数。 指定的日期范围

尝试:

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

实现这一目标的最快,最有效的方法是什么?欢迎任何建议,谢谢你的时间

3 个答案:

答案 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