要求列数据相对于列数据并排

时间:2018-11-28 01:38:44

标签: sql sql-server

我有如下示例数据,其中一个WPID的PLO和状态字段。

PR       PN       WPID   WPN           PLO  Status
1233    12331   5377820 12331-abc-1-c   a1  PP
1233    12331   5377820 12331-abc-1-c   b1  RTS
1233    12331   5377820 12331-abc-1-c   c1  Hold
1233    12331   5377820 12331-abc-1-c   d1  Completed
1233    12331   5377820 12331-abc-1-c   e1  Review
1233    12331   5377820 12331-def-1-c   b1  RTS

如何获得如下所示的结果,其中每个PLO和状态并排。 有什么办法吗?

PR       PN     WPID    WPN             PLO1 Status1 PLO2 Status2 PLO3 Status3
1233    12331   5377820 12331-abc-1-c   a1   PP      b1  RTS      d1     Completed
1233    12331   5377820 12331-abc-1-c   c1   Hold                           
1233    12331   5377820 12331-abc-1-c   e1   Review
1233    12331   5377820 12331-def-1-c                b1  RTS

2 个答案:

答案 0 :(得分:0)

从表面上看,这似乎需要稍作更改的数据透视查询,并且可以通过遵循以下模式将表自身不连接来实现:

SELECT
   pr, pn, wpid, wpn,
   --all PLO that should appear in same column go in each IN
   MAX(CASE WHEN plo IN ('a1','c1','e1') THEN plo END) as plo1,
   MAX(CASE WHEN plo IN ('a1','c1','e1') THEN status END) as status1,
   MAX(CASE WHEN plo IN ('b1') THEN plo END) as plo2,
   MAX(CASE WHEN plo IN ('b1') THEN status END) as status2,
   MAX(CASE WHEN plo IN ('d1') THEN plo END) as plo3,
   MAX(CASE WHEN plo IN ('d1') THEN status END as status3
FROM
  table
GROUP BY
  pr, pn, wpid, wpn,
  CASE --all PLO that should appear on same row go in same IN, if adding another WHEN increment the number at line end too
    WHEN plo IN ('a1','b1','d1') THEN 1
    WHEN plo IN ('c1') THEN 2
    WHEN plo IN ('e1') THEN 3
  END

演示:https://www.db-fiddle.com/f/nK39QrjcxpZgkRokStXQhB/0

要扩展此功能,请按照注释中编写的规则,在选择列表中添加更多的MAX CASE WHEN(以添加更多的列),并在GROUP BY中为案例添加更多的WHEN子句(以创建更多的行)

答案 1 :(得分:0)

选择 公关 plo, 情况何时 plo ='a1'然后'a1'结尾为PLO1

来自NewTable t1