SQL-将两个表合并为一个输出

说我有两个表:

已知时间:

ChargeNum    CategoryID    Month    Hours
111111       1             2/1/09   10
111111       1             3/1/09   30
111111       1             4/1/09   50
222222       1             3/1/09   40
111111       2             4/1/09   50

未知时间:

ChargeNum   Month   Hours
111111      2/1/09  70
111111      3/1/09  40.5
222222      7/1/09  25.5

我需要将这些时间(忽略月份)分组到一个数据表中,以便获得以下预期结果:

ChargeNum    CategoryID     Hours
111111       1              90
111111       2              50
111111       Unknown        110.5
222222       1              40
222222       Unknown        25.5

我似乎无法弄清楚。 任何帮助将不胜感激!

编辑:我需要总结每个ChargeNum /类别组合的小时数。 我更新了示例数据以反映这一点。

Matthew Jones asked 2020-06-27T23:49:56Z
3个解决方案
81 votes

您将需要使用UNION ALL来组合两个查询的结果。 在您的情况下:

SELECT ChargeNum, CategoryID, SUM(Hours)
FROM KnownHours
GROUP BY ChargeNum, CategoryID
UNION ALL
SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
FROM UnknownHours
GROUP BY ChargeNum

注意-如果您如上所述使用UNION ALL,它不会比单独运行两个查询慢,因为它不会重复检查。

lc. answered 2020-06-27T23:50:16Z
11 votes

在预期的输出中,您倒数第二行的总和不正确,根据表中的数据应为40,但这是查询:

Select  ChargeNum, CategoryId, Sum(Hours)
From    (
    Select  ChargeNum, CategoryId, Hours
    From    KnownHours
    Union
    Select  ChargeNum, 'Unknown' As CategoryId, Hours
    From    UnknownHours
) As a
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId

这是输出:

ChargeNum  CategoryId 
---------- ---------- ----------------------
111111     1          40
111111     2          50
111111     Unknown    70
222222     1          40
222222     Unknown    25.5
BenAlabaster answered 2020-06-27T23:50:40Z
1 votes

我们可以进一步走吗,说我只想查看合并后具有50小时或更长时间的行...我已经尝试过了,但是却收到一条错误消息,它找不到SumHours ...

Select  ChargeNum, CategoryId, Sum(Hours) As SumHours
From    (
    Select  ChargeNum, CategoryId, Hours
    From    KnownHours
    Union
    Select  ChargeNum, 'Unknown' As CategoryId, Hours
    From    UnknownHours
) As a
WHERE (SumHours>=50)
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId

所以我尝试了

    Select  ChargeNum, CategoryId, Sum(Hours) As SumHours
From    (
    Select  ChargeNum, CategoryId, Hours
    From    KnownHours
    Union
    Select  ChargeNum, 'Unknown' As CategoryId, Hours
    From    UnknownHours
) As a
WHERE (Hours>=50)
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId

但这并没有给出两个表的总和...

AccessProgrammer answered 2020-06-27T23:51:09Z
translate from https://stackoverflow.com:/questions/1227835/combine-two-tables-for-one-output