将值添加到分组列

时间:2014-01-15 18:24:15

标签: sql sql-server group-by grouping

我遇到很多麻烦,我认为你们中的一些人可能会遇到过。

(关于商业旅行的全部内容,两张桌子,一张是商务旅行中付款,另一张是关于商务旅行,所以第一张有比另一张更多的行,(还有更多付款发生)比旅行)) 我有两个表,表A和表B.

表A如下所示

| TableA_ID | TableB_ID | PaymentMethod | ValuePayed  |
| 52        | 1         | Method1       |   23,2      |
| 21        | 1         | Method2       |   23,2      |
| 33        | 2         | Method3       |   23,2      |
| 42        | 1         | Method2       |   14        |
| 11        | 14        | Method1       |   267       |
| 42        | 1         | Method2       |   14,7      |
| 13        | 32        | Method1       |   100,2     |

表B看起来像这样

 | TableB_ID | TravelExpenses | OperatingExpense |
 |  1        |  23            |   12             |
 |  1        | 234            |   24             |
 |  2        |  12            |    7             |
 |  1        | 432            |   12             |
 | 14        | 110            |   12             |

我正在尝试创建一个如下所示的度量表(表C):

 | TableC_ID |    TypeofCost   |     Amount       |
 |  1        | Method1         |   100,2          |
 |  2        | Method2         |   52             |
 |  3        | TravelExpenses  |    7             |
 |  4        | OperatingExpense|   12             |
 |  5        | Method3         |   12             |
 |  6        | OperatingExpense|   7              |
 |  7        | Method3         |   12             |

(金额结果将被汇总和列 - 员工,月, TypeofCost 分组)

所以我不仅要通过表A中的PaymentMethod进行分组, 但也要在组中插入新值(TravelExpensesOperatingExpense

有人能告诉我如何在SQL中完成这项工作吗?

这是我到目前为止所尝试的内容

SELECT PaymentMethod as TypeofCost
      ,Sum(ValuePayed) as Amount
FROM   TableA Left Outer Join TableB on TableA.TableB_ID = TableB.TableB_ID
GROUP  PaymentMethod

UNION 

SELECT 'TravelExpenses' as TypeofCost
       ,Sum(TableB.TravelExpenses) as Amount
FROM   TableA Left Outer Join TableB on TableA.TableB_ID = TableB.TableB_ID
GROUP  PaymentMethod

UNION

SELECT 'OperatingExpense' as TypeofCost
       ,Sum(TableB.OperatingExpense) as Amount
FROM   TableA Left Outer Join TableB on TableA.TableB_ID = TableB.TableB_ID
GROUP  PaymentMethod

1 个答案:

答案 0 :(得分:1)

它应该是这样的:

Select
    row_number() OVER(ORDER BY TableB_ID) as 'TableC_ID',
    u.TypeofCost,
    u.Amount
  from (
        Select
            a.TableB_ID,
            a.PaymentMethod as 'TypeofCost',
            SUM(a.ValuePayed) as 'Amount'
        from
            Table_A as a
        group by a.TableB_ID, a.PaymentMethod

        union

        Select
            b1.TableB_ID,
            'TravelExpenses' as 'TypeofCost',
            SUM(b1.TravelExpenses) as 'Amount'
        from
            Table_B as b1
        group by b1.TableB_ID

        union

        Select
            b2.TableB_ID,
            'OperatingExpenses' as 'TypeofCost',
            SUM(b2.OperatingExpenses) as 'Amount'
        from
            Table_B as b2
        group by b2.TableB_ID
    ) as u

编辑:生成TableC_ID