连接表中多个记录的总和?

时间:2012-10-02 11:46:23

标签: sql

我有这样的查询:

select a,b,c
from
table

现在我有另一张桌子,里面有几个小时。基本上我想要anotherTable.hoursWorked的总和,其中anotherTable.a = a和anotherTable.b = b和anotherTable.c = c。

我需要做什么样的查询?

由于

这样的事情:

SELECT DATE, CUSTOMER, SUM(FKEY.HOURSWORKED)
FROM TABLE1
INNER JOIN TABLE2 FKEY ON FKEY.CUSTOMER = CUSTOMER, FKEY.DATE = DATE

2 个答案:

答案 0 :(得分:1)

你会写这样的东西:

SELECT SUM(at.hoursWorked)
FROM
    anotherTable at
    JOIN (SELECT a, b, c FROM thisTable) t
    ON at.a = t.a AND at.b = t.b AND at.c = t.c

答案 1 :(得分:0)

修改示例SQL以使其正常工作:

SELECT TABLE1.DATE, TABLE1.CUSTOMER, SUM(FKEY.HOURSWORKED) AS HOURSWORKED
FROM TABLE1
INNER JOIN TABLE2 FKEY
ON FKEY.CUSTOMER = TABLE1.CUSTOMER AND FKEY.DATE = TABLE1.DATE
GROUP BY TABLE1.DATE, TABLE1.CUSTOMER

最重要的变化是我添加了GROUP BY条款。