我的任务估计需要几个小时。花费的时间减去估计应该会花费时间。
员工表
CREATE TABLE sign
(signid varchar(3), signname varchar(30));
INSERT INTO sign
(signid, signname)
VALUES
('AA', 'Adam'),
('BB', 'Bert'),
('CC', 'Cecil'),
('DD', 'David')
任务表
CREATE TABLE task
(taskid int4, taskdate date, tasksign varchar(3), taskhr numeric(10,2));
INSERT INTO task
(taskid, taskdate, tasksign, taskhr)
VALUES
(1,'2016-01-01','AA',10),
(2,'2016-02-01','BB',10),
(3,'2016-01-15','BB',10),
(4,'2016-03-01','BB',10),
(5,'2016-01-03','CC',10)
时间表表格
CREATE TABLE hr
(hrid int4, hrsign varchar(3), hrtask int4, hrqty numeric(10,2));
INSERT INTO hr
(hrid, hrsign, hrtask, hrqty)
VALUES
(1,'AA',1,1.1),
(2,'BB',2,1.2),
(3,'CC',5,2.3),
(4,'CC',5,5)
我试图从估计的时间中减去花费的时间的简单查询给出了错误的答案:
SELECT signid,signname,to_char(taskdate, 'iyyy-iw'),sum(taskhr),sum(hrqty)
FROM sign
LEFT JOIN task ON tasksign=signid
LEFT JOIN hr ON taskid=hrtask
GROUP BY 1,2,3
ORDER BY 2,3
答案是:
id name week task hr
AA Adam 2015-53 10 1,1000
BB Bert 2016-02 10 NULL
BB Bert 2016-05 10 1,2000
BB Bert 2016-09 10 NULL
CC Cecil 2015-53 20 7,3000
DD David NULL NULL NULL
任务时间似乎重复。它应该是这样的:
id name week task hr
AA Adam 2015-53 10 1,1000
BB Bert 2016-02 10 NULL
BB Bert 2016-05 10 1,2000
BB Bert 2016-09 10 NULL
CC Cecil 2015-53 10 7,3000
DD David NULL NULL NULL
如何提出计算正确的查询?
“小提琴”
答案 0 :(得分:2)
加入hr
表将task
表行相乘。加入前汇总hr
:
select signid, signname, to_char(taskdate, 'iyyy-iw'), sum(taskhr), sum(hrqty)
from
sign
left join
task on tasksign = signid
left join (
select hrtask, sum(hrqty) as hrqty
from hr
group by 1
)
hr on taskid = hrtask
group by 1,2,3
order by 2,3
;
signid | signname | to_char | sum | sum
--------+----------+---------+-------+------
AA | Adam | 2015-53 | 10.00 | 1.10
BB | Bert | 2016-02 | 10.00 |
BB | Bert | 2016-05 | 10.00 | 1.20
BB | Bert | 2016-09 | 10.00 |
CC | Cecil | 2015-53 | 10.00 | 7.30
DD | David | | |