简体   繁体   中英

HAVING clause on SUM column

I want to have a condition on my score column that I get from sum, but HAVING score =< 1 is not working if I put it after group by. That would have to show me projects that have good score. I am using hsqldb, what's going wrong? I get 'user lacks privelege or object not found: SCORE'

SELECT p.id, p.project_name, SUM(CASE r.type_code 
    WHEN 'GOOD' THEN  1 
    WHEN 'VERY_GOOD' THEN  1 
    WHEN 'BAD' THEN -1 
    WHEN 'VERY_BAD' THEN -1 
    ELSE 0 END) AS score
FROM record_project AS rp
JOIN project AS p ON p.id = rp.project_id 
JOIN record AS r ON r.id = rp.record_id 
GROUP BY p.id, p.project_name
HAVING score =< 1        <<<---- wrong?!
ORDER BY score DESC LIMIT 1

You should be using the whole calculated column,

SELECT p.id, p.project_name,
       SUM(CASE WHEN r.type_code IN ('GOOD','VERY_GOOD') THEN 1
                WHEN r.type_code IN ('BAD','VERY_BAD') THEN -1
                ELSE 0 END) score
FROM   record_project AS rp
       JOIN project AS p ON p.id = rp.project_id 
       JOIN record AS r ON r.id = rp.record_id 
GROUP  BY p.id, p.project_name
HAVING SUM(CASE WHEN r.type_code IN ('GOOD','VERY_GOOD') THEN 1
                WHEN r.type_code IN ('BAD','VERY_BAD') THEN -1
                ELSE 0 END) <= 1
ORDER  BY score DESC 
-- LIMIT  1

You can incorporate the HAVING as a WHERE over a subquery:

SELECT * FROM ( 
  SELECT p.id, p.project_name, SUM(CASE r.type_code 
    WHEN 'GOOD' THEN  1 
    WHEN 'VERY_GOOD' THEN  1 
    WHEN 'BAD' THEN -1 
    WHEN 'VERY_BAD' THEN -1 
    ELSE 0 END) AS score
  FROM record_project AS rp
  JOIN project AS p ON p.id = rp.project_id 
  JOIN record AS r ON r.id = rp.record_id 
  GROUP BY p.id, p.project_name) x
WHERE score =< 1
ORDER BY score DESC
LIMIT 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM