两个表中两列的总和

时间:2017-06-23 14:29:18

标签: sql

我试图获得两列的总和,但似乎添加不正确。我有一个临时表#temp和另一个名为workHours的表。

在#temp:

emplyID | hours | projID | date
2       |  3    |  5     | 2015-01-01
5       |  5    |  5     | 2015-03-02    
3       |  4    |  5     | 2015-06-02
9       |  3    |  5     | 2015-05-03
2       |  3    |  5     | 2015-01-01
5       |  5    |  5     | 2015-02-02
3       |  4    |  5     | 2015-06-02
9       |  3    |  5     | 2015-06-03

workHours表:

emplyID | hours | projID | date
3       |  4    |  5     | 2015-06-02
9       |  3    |  5     | 2015-06-03
2       |  3    |  5     | 2015-01-01
5       |  5    |  5     | 2015-02-02
2       |  3    |  5     | 2015-01-01
5       |  5    |  5     | 2015-02-02     
3       |  4    |  5     | 2015-06-02
9       |  3    |  5     | 2015-06-03

这就是我的尝试:

select c.FirstName, a.employeeID, a.hours as workHours, b.hours as 
tempWorkHours, a.hours+b.hours as totalHours, a.date 
from workHours as a, #temp as b, employee as c
where a.employeeID=c.employeeID and a.employeeID=b.employeeID

然而,这似乎抓住了第一张桌子的第一个小时,并将其添加到第二张桌子上的每个小时,然后抓住第二张桌子反之亦然。

预期结果应为例如:

emplyID | hours
  2    |   12
  3    |   16
  5    |   20
  9    |   12

我该如何解决这个问题?非常感谢。

4 个答案:

答案 0 :(得分:1)

您需要使用UNION ALL代替INNER JOIN

select emplyID,sum(totalHours)
From
(
select emplyID, 
       hours as totalHours
from workHours as a 
union all
select emplyID, 
       hours as totalHours
From #temp as b
) a
Group by emplyID

答案 1 :(得分:0)

您可以使用逗号(,)生成笛卡尔积延迟。

SELECT SUM(A.HOURS+B HOURS) FROM TEMP AS A  JOIN WORKTABLE AS B ON A.EMPID = B.EMPID

答案 2 :(得分:0)

#tempworkHours之间有部分交叉联接。我怀疑你会想做这样的事情:

select c.FirstName,
    a.employeeID,
    a.hours as workHours,
    b.hours as tempWorkHours,
    a.hours + b.hours as totalHours,
    a.date 
from workHours as a
    inner join #temp as b
        on  a.employeeID = b.employeeID
        and a.projID     = b.projID
        and a.date       = b.date
    inner join employee as c
        on  a.employeeID = c.employeeID 

现在,我无法确切知道workHours#temp之间需要加入哪些字段。我也无法知道你是否需要外连接。我也猜测你当前查询的所需输出。

最后,避免使用逗号连接。这是一种古老的语法,大多数人都觉得难以阅读。

编辑:根据您更新的预期输出,我试试这个:

select c.FirstName,
    a.employeeID,
    sum(a.hours + b.hours) as totalHours,
from workHours as a
    inner join #temp as b
        on  a.employeeID = b.employeeID
        and a.projID     = b.projID
        and a.date       = b.date
    inner join employee as c
        on  a.employeeID = c.employeeID 
group by a.employeeID,
    c.FirstName

答案 3 :(得分:0)

我认为你错过了加入条件

 SELECT
    c.FirstName,
    a.employeeID, 
    SUM(a.hours) as workHours, 
    SUM(b.hours) as tempWorkHours, 
    SUM(a.hours+b.hours) as totalHours, 
    a.date 
    FROM workHours as a
    OUTER JOIN #temp as b ON a.employeeID=b.employeeID AND a.date = b.date
    INNER JOIN employee as c ON a.employeeID=c.employeeID AND a.date = c.date
    GROUP BY a.employeeID

如果您的员工ID不够独特,那么每列都有唯一的配对,那么添加更多的连接条件。

编辑:进一步加入条件