【问题标题】:How to Merge Identical Rows with different column?如何合并具有不同列的相同行?
【发布时间】:2020-05-13 16:49:50
【问题描述】:

我有一张这样的桌子:

--------------------------------------------
| Job | Class | Employee | PayType | Hours |
| 212     A      John         1        20  |
| 212     A      John         2        10  |
| 911     C      Rebekah      1        15  |
| 911     C      Rebekah      2        10  |
--------------------------------------------

我想转换此表,以便获得以下输出

------------------------------------
| Job | Class | Employee | OT | ST |
| 212 |   A   | John     | 20 | 10 |
| 911 |   C   | Rebekah  | 15 | 10 |
------------------------------------

这里我为 OT 设置了 1,为 ST 设置了 2

【问题讨论】:

  • 你用 pivot 标记了这个,所以我想你知道这是需要做的——你在旋转时遇到了问题吗?

标签: sql sql-server tsql pivot aggregate-functions


【解决方案1】:

你可以条件聚合:

select 
    job,
    class,
    employee
    sum(case when paytype = 1 then hours else 0 end) ot,
    sum(case when paytype = 2 then hours else 0 end) st
from mytable
group by
    jobs,
    class,
    employee

【讨论】:

    【解决方案2】:

    使用PIVOT TABLE

    select 
       Job,
       Class,
       Employee,
       [1] as OT, 
       [2] as ST from
       (
          select * from test2
       ) as t
       pivot
       (
          sum([Hours])
          for paytype in([1],[2])
       ) as pvt;
    

    【讨论】:

      猜你喜欢
      • 2022-12-16
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 2020-11-17
      • 1970-01-01
      • 2020-12-23
      相关资源
      最近更新 更多