如何合并具有不同列的相同行?

Posted

技术标签:

【中文标题】如何合并具有不同列的相同行?【英文标题】: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 标记了这个,所以我想你知道这是需要做的——你在旋转时遇到了问题吗? 【参考方案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;

【讨论】:

以上是关于如何合并具有不同列的相同行?的主要内容,如果未能解决你的问题,请参考以下文章