将两个表合并为一个输出
说我有两个表:
KnownHours:
ChargeNum类别ID月时 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月时 111111 2/1/09 70 111111 3/1/09 40.5 222222 7/1/09 25.5
我需要将这些小时数(忽略Month)分组到一个数据表中,以便我的预期结果如下:
ChargeNum类别ID小时 111111 1 90 111111 2 50 111111未知110.5 222222 1 40 222222未知25.5
我似乎无法弄清楚这一点。 任何帮助将不胜感激!
编辑:我需要总结每个ChargeNum /类别组合的小时。 我更新了样本数据以反映这一点。
您需要使用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
,那么不会比分别运行两个查询慢,因为它没有重复检查。
在预期的输出中,第二行的总和不正确,根据表中的数据应该是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
我们可以更进一步说,我只想看到合并时有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
但是这并没有给出两个表上的时间总和…