我需要将查询结果插入表Employee
。
以这种方式创建Employee
表:
CREATE TABLE Employee(
Name1 NVARCHAR(100)
, Date1 DATETIME
, Name2 NVARCHAR(100)
, Date2 DATETIME
, Name3 NVARCHAR(100)
, Date3 DATETIME
, Name4 NVARCHAR(100)
, Date4 DATETIME
, Name5 NVARCHAR(100)
, Date5 DATETIME
, Name6 NVARCHAR(100)
, Date6 DATETIME
, Name7 NVARCHAR(100)
, Date7 DATETIME
)
为了简单起见,我们可以说我的查询是:
SELECT d.name, d.date
FROM data d
WHERE d.type = 'n'
ORDER BY d.name
此查询返回如下内容:
A DateA
B DateB
C DateC
D DateD
E DateE
F DateF
G DateG
H DateH
I DateI
L DateL
M DateM
N DateN
O DateO
P DateP
Q DateQ
QQ DateQQ
...
...
棘手的部分是我应该以这种方式在Employee
表中插入每一行:
这意味着在每个row_num%7 = 0之后,我需要从Name1和Day1开始再次循环(不知何故)。
预期结果(在我的Employee表中)应为:
A,DateA, B,DateB, C,DateC, D,DateD, E,DateE, F,DateF, G,DateG
H,DateH, I,DateI, L,DateL, M,DateM, N,DateN, O,DateO, P,DateP
Q,DateQ, QQ,DateQQ, R,DateR, S,DateS, T,DateT, U,DateU, V,DateV
W,DateW, X,DateX, Y,DateY, YY,DateYY, Z,DateZ, ZZ,DateZZ, ZZZ,DateZZZ
....
我不知道如何处理这个问题,但是我需要在该表中输出(或者如果它更有帮助,可以在7个不同的表中)。
我希望我表达清楚。
答案 0 :(得分:0)
你可以花大约30分钟思考一下基于直接设置的方法,或者在5分钟内创建一个简单的循环。
DECLARE @Loops INT=(SELECT (COUNT(*) / 7)+CASE WHEN(COUNT(*) % 7)>0 THEN 1 ELSE 0 END FROM MyOtherTable)
DECLARE @LoopCount INT=0
WHILE( @LoopCount <= @Loops )BEGIN
SET @LoopCount=@LoopCount+1
INSERT Employee(name,date)
SELECT
name,date
FROM
(
SELECT
name,
date,
InsertLoop=NTILE(@Loops) OVER(ORDER BY MyTableID)
FROM
MyOtherTable
)AS X
WHERE X.InsertLoop=@LoopCount
END
答案 1 :(得分:0)
在一个声明中(我认为这是Lucky所考虑的):
With Src As ( --< Source query with RowNum and ColNum calculated through ROW_NUMBER()
SELECT e.name, e.date
, (ROW_NUMBER() Over (Order By Name, Date) - 1) % 7 + 1 As ColNum
, FLOOR((ROW_NUMBER() Over (Order By Name, Date) - 1) / 7) As RowNum
FROM employee e
WHERE e.type = 'n'
)
Select
Src1.Name As Name1, Src1.Date As Date1
, Src2.Name As Name2, Src2.Date As Date2
, Src3.Name As Name3, Src3.Date As Date3
, Src4.Name As Name4, Src4.Date As Date4
, Src5.Name As Name5, Src5.Date As Date5
, Src6.Name As Name6, Src6.Date As Date6
, Src7.Name As Name7, Src7.Date As Date7
From Src Src1
Left Join Src Src2 On Src1.RowNum = Src2.RowNum And Src2.ColNum = 2
Left Join Src Src3 On Src1.RowNum = Src3.RowNum And Src3.ColNum = 3
Left Join Src Src4 On Src1.RowNum = Src4.RowNum And Src4.ColNum = 4
Left Join Src Src5 On Src1.RowNum = Src5.RowNum And Src5.ColNum = 5
Left Join Src Src6 On Src1.RowNum = Src6.RowNum And Src6.ColNum = 6
Left Join Src Src7 On Src1.RowNum = Src7.RowNum And Src7.ColNum = 7
Where Src1.ColNum = 1