Combine two tables for one output

后端 未结 2 1405
情深已故
情深已故 2020-11-29 03:03

Say I have two tables:

KnownHours:

ChargeNum    CategoryID    Month    Hours
111111       1             2/1/09   10
111111       1             3/1/09   30         


        
2条回答
  •  离开以前
    2020-11-29 03:33

    In your expected output, you've got the second last row sum incorrect, it should be 40 according to the data in your tables, but here is the query:

    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
    

    And here is the output:

    ChargeNum  CategoryId 
    ---------- ---------- ----------------------
    111111     1          40
    111111     2          50
    111111     Unknown    70
    222222     1          40
    222222     Unknown    25.5
    

提交回复
热议问题