【发布时间】:2014-07-26 17:31:43
【问题描述】:
我在 SQL Server 2014 中有一个名为 anotes 的表,其中包含以下数据
我想将此数据添加到另一个名为 final 的表中
ID Notes NoteDate
text1, text2, text3, text4 进入决赛桌的Notes 列,Notedate1,notedate2,notedate3,notedate4 进入Notedate 列。
我尝试先用注释对数据进行反透视:
select createdid, temp
from (select createdid,text1,text2,text3,text4 from anotes) p
unpivot
(temp for note in(text1,text2,text3,text4)) as unpvt
order by createdid
这给了我正确的结果:
然后对于日期部分,我使用了另一个非透视查询:
select createdid,temp2
from (select createdid,notedate1,notedate2,notedate3,notedate4 from anotes) p
unpivot (temp2 for notedate in(notedate1,notedate2,notedate3,notedate4)) as unpvt2
这也给了我正确的结果:
现在我想将此数据添加到我的最终表格中。
我尝试了以下查询,结果是交叉连接:(
select a.createdid, a.temp, b.temp2
from (select createdid, temp
from (select createdid,text1,text2,text3,text4 from anotes) p
unpivot
(temp for note in(text1,text2,text3,text4)) as unpvt) a inner join (select createdid,temp2
from (select createdid,notedate1,notedate2,notedate3,notedate4 from anotes) p
unpivot (temp2 for notedate in(notedate1,notedate2,notedate3,notedate4)) as unpvt) b on a.createdid=b.createdid
输出如下:
有什么方法可以同时对两列进行反透视?
或者使用两个选择查询将该数据添加到我的最终表格中?
提前致谢!
【问题讨论】:
-
试试this blog 或者只搜索SQL Multiple Unpivot
-
感谢@AHiggins 的链接,工作就像一个魅力!
标签: sql tsql unpivot sql-server-2014