SQL SERVER-使用PIVOT将列拆分为多个

时间:2019-06-20 12:12:26

标签: sql sql-server subquery pivot

一个数据库表由一列具有ID的值组成,该ID与包含这些值名称的辅助表相关。例如,我有一个收件人,其中有24行,每行都按名称与单独的值类型相关。

我正在尝试改进子查询,因为我对大型复杂查询非常陌生,因此我无法解决如何将这些值拆分为该ONE收件人的新列。

我尝试了PIVOT表,我不确定这是否是前进的最佳方法,所以如果有人有其他选择,请告诉我,以便我进行研究!

当前查询产生以下内容:

SELECT e.recipientid, 
svr.segvaluebagid, 
svr.segvalueid, 
sv.segid, 
s.NAME, 
sv.value 
FROM   SCHEMA.DB.TABLE e 
   LEFT JOIN SCHEMA.DB.TABLE svr 
   ON svr.segvaluebagid = e.segvaluebagid 
   LEFT JOIN SCHEMA.DB.TABLE sv 
   ON svr.segvalueid = sv.segvalueid 
   LEFT JOIN SCHEMA.DB.TABLE s 
   ON s.segid = sv.segid 
WHERE  e.marketingcampaignid = 01
  AND e.recipientid = 01
  AND s.NAME NOT LIKE '%useragent%' 
GROUP  BY e.recipientid, 
              e.eventid, 
              e.eventtypeid, 
              e.marketingcampaignid, 
              e.jobid, 
              e.segvaluebagid, 
              e.triggerdate, 
              svr.segvaluebagid, 
              svr.segvalueid, 
              sv.segid, 
              s.NAME, 
              sv.value

ID,ID2,ID3,ID4,COL NAME ,COL VALUE
ID,ID2,ID3,ID4,DIFFERENT COL NAME ,DIFFERENT COL VALUE
ID,ID2,ID3,ID4,DIFFERENT COL NAME ,DIFFERENT COL VALUE
ID,ID2,ID3,ID4,DIFFERENT COL NAME ,DIFFERENT COL VALUE
ID,ID2,ID3,ID4,DIFFERENT COL NAME ,DIFFERENT COL VALUE
ID,ID2,ID3,ID4,DIFFERENT COL NAME ,DIFFERENT COL VALUE
ID,ID2,ID3,ID4,DIFFERENT COL NAME ,DIFFERENT COL VALUE

我在查询中加入了以下PIVOT代码:

PIVOT(max([value])
FOR [name] IN([COL], 
[COL1], 
[COL2], 
[COL3], 
[COL4], 
[COL5], 
[COL6], 
[COL7], 
[COL8], 
[COL9], 
[COL10]))

查询现在为每个值生成一个新列,同时还保持每一行,如下所示:

VALUE,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,VALUE,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,VALUE,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,VALUE,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,VALUE,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,VALUE,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

我的理想输出如下:

VALUE,VALUE,VALUE,VALUE,VALUE,VALUE,VALUE,VALUE,VALUE,VALUE,VALUE

我真的为此感到困惑,如果有人能提供一点见识,我将非常感激。

0 个答案:

没有答案