PostgreSQL version 9.1.13
I have one table code that are linked to several tables that I want to sum.
So far I get a result but not correct values (jsfiddle)
http://sqlfiddle.com/#!15/efedc/18
SELECT code_name,
SUM(estrec_sum) as est,
SUM(hr_sum) as total,
SUM(case when hr_status='0' then hr_sum ELSE 0 END) as unbill,
SUM(case when hr_status='1' then hr_sum ELSE 0 END) as bill
FROM code
RIGHT JOIN hr ON code_id=hr_code
RIGHT JOIN estrec ON code_id=estrec_code
WHERE hr_job='1' AND estrec_job='1'
GROUP BY code_name
The sum of estrec_sum does sum all estrec_job and the hr_status is ignored
Further testing: Running each table separate gets correct values:
SELECT code_name,
SUM(case when estrec_job = '1' then estrec_sum else 0 end) as est
FROM code
RIGHT JOIN estrec ON code_id=estrec_code
WHERE estrec_job = '1'
GROUP BY code_name
ORDER BY code_name
Copy gets 100 on job 1 as expected.
SELECT code_name,
SUM(case when hr_job = '1' then hr_sum else 0 end) as total,
SUM(case when hr_job = '1' and hr_status='0' then hr_sum ELSE 0 END) as unbill,
SUM(case when hr_job = '1' and hr_status='1' then hr_sum ELSE 0 END) as bill
FROM code
RIGHT JOIN hr ON code_id=hr_code
WHERE hr_job = '1'
GROUP BY code_name
the result is also correct. But fetching from two tables gets wrong values back.
It seems that adding another RIGHT JOIN destroys the result
Thanks in advance for any clues!
code,hr,estrecand tell me what wrong is the output.