从几个表中获取错误的总和 - postgresql

时间:2014-11-27 09:17:20

标签: postgresql

PostgreSQL版本9.1.13

我有一个表代码链接到我想要求和的几个表。

到目前为止,我得到的结果却没有正确的值(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

estrec_sum的总和会对所有estrec_job求和,并忽略hr_status

进一步测试:分别运行每个表得到正确的值:

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

按预期复制在作业1上获得100。

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

结果也是正确的。但是从两个表中取出会得到错误的值。

似乎添加另一个RIGHT JOIN会破坏结果

提前感谢任何线索!

4 个答案:

答案 0 :(得分:2)

SQL Fiddle

select
    code_name,
    est,
    unbill + bill as total,
    unbill,
    bill
from
    code
    right outer join (
        select
            hr_code as code_id,
            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 hr
        where hr_job = '1'
        group by hr_code
) hr using (code_id)
    right outer join (
        select
            estrec_code as code_id,
            sum(estrec_sum) as est
        from estrec
        where estrec_job = '1'
        group by estrec_code
    ) estrec using (code_id)
;

答案 1 :(得分:0)

我找到了一些解决方案:

SELECT code_name, 
(SELECT sum(estrec_sum) from estrec where estrec_code = code_id and estrec_job = '1') as est, 
(SELECT sum(hr_sum) from hr where hr_code=code_id  and hr_job= '1') as total,
(SELECT sum(hr_sum) from hr where hr_status='0' and hr_code = code_id and hr_job= '1') as unbill,
(SELECT sum(hr_sum) from hr where hr_status='1' and hr_code = code_id and hr_job= '1') as bill
FROM code

虽然这会导致"空行"。我如何摆脱它们?

答案 2 :(得分:0)

非常感谢!我印象深刻!

只要hr表中有相应的代码,此查询就可以完美运行。添加" WEB"工作1打破了代码。并且它不会获取" code_name"这一行。

http://sqlfiddle.com/#!1/8cfe2/1

答案 3 :(得分:0)

来自Clodoaldo Neto的“右外连接”的原始解决方案给出了不完整的结果。

http://sqlfiddle.com/#!1/fd6f7/1(Clodoaldo Neto但改为左外连接)

http://sqlfiddle.com/#!1/fd6f7/2(我的解决方案)

知道如何摆脱“空行”吗?