将两个表合并为一个输出

时间:2009-08-04 14:25:20

标签: sql union

说我有两张桌子:

KnownHours:

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

UnknownHours:

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 / Category组合的小时数相加。我更新了样本数据以反映这一点。

3 个答案:

答案 0 :(得分:77)

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

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,则不会比单独运行两个查询慢,因为它没有重复检查。

答案 1 :(得分:11)

在您的预期输出中,您的第二行总和不正确,根据表中的数据它应该是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

答案 2 :(得分:1)

我们可以更进一步,并说我只想看到50小时或更长时间合并的行...我试过这个,但得到一个错误,它无法找到SumHours ...... < / p>

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

但这并没有给出两张桌子上的小时总和......