我在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
这给了我正确的结果:
然后对于日期部分我使用了另一个unpivot查询:
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
输出如下:
有什么方法可以同时对两个列进行同步?
或者使用两个选择查询将该数据添加到我的最终表中?
提前致谢!
答案 0 :(得分:3)
我想说最简洁,也许是最有效的方法来取消多列的删除是使用CROSS APPLY和table valued constructor:
SELECT t.CreatedID, upvt.Text, upvt.NoteDate
FROM anotes t
CROSS APPLY
(VALUES
(Text1, NoteDate1),
(Text2, NoteDate2),
(Text3, NoteDate3),
(Text4, NoteDate4),
(Text5, NoteDate5),
(Text6, NoteDate6),
(Text7, NoteDate7)
) upvt (Text, NoteDate);
<强> Simplified Example on SQL Fiddle 强>
<强>附录强>
我觉得这个概念很难解释,但我会试试。值为constuctor的表只是一种动态定义表的方法,所以
SELECT *
FROM (VALUES (1, 1), (2, 2)) t (a, b);
将使用带有数据的别名t创建一个表:
a b
------
1 1
2 2
因此,当您在APPLY中使用它时,您可以访问所有外部列,因此只需使用正确的值对定义构造的表(即text1 with date1)。
答案 1 :(得分:0)
使用@AHiggins上面提到的链接
以下是我的最终查询!
select createdid,temp,temp2
from (select createdid,text1,text2,text3,text4,text5,text6,text7,notedate1,notedate2,notedate3,notedate4,notedate5,notedate6,notedate7 from anotes) main
unpivot
(temp for notes in(text1,text2,text3,text4,text5,text6,text7)) notes
unpivot (temp2 for notedate in(notedate1,notedate2,notedate3,notedate4,notedate5,notedate6,notedate7)) Dates
where RIGHT(notes,1)=RIGHT(notedate,1)
答案 2 :(得分:0)
将每个查询视为一个表,并根据createdid和fieldid(字段名称的数字部分)将它们连接在一起。
select x.createdid, x.textValue, y.dateValue
from
(
select createdid, substring(note, 5, len(note)) fieldId, textValue
from (select createdid,text1,text2,text3,text4 from anotes) p
unpivot
(textValue for note in(text1,text2,text3,text4)) as unpvt
)x
join
(
select createdid, substring(notedate, 9, len(notedate)) fieldId, dateValue
from (select createdid,notedate1,notedate2,notedate3,notedate4 from anotes) p
unpivot (dateValue for notedate in(notedate1,notedate2,notedate3,notedate4)) as unpvt2
) y on x.fieldId = y.fieldId and x.createdid = y.createdid
order by x.createdid, x.fieldId
如果列数太多且字段名称的最右边数字重复(例如text1和text11),则给出的其他答案将无效。