我有这种TSQL语法:
WITH cte AS(
SELECT Stamps, row_number() over (order by (SELECT 1)) rn from week
unpivot
(Stamps FOR Day IN ([Sun], [Mon], [Tue], [Wed], [Thu], [Fri], [Sat]) ) AS unpvt )
SELECT Stamps + ': ' +STUFF((SELECT ','+cast(rn as varchar(9)) from cte where Stamps=A.TimeStamps FOR XML PATH('')), 1 , 1 , '' ) from cte A group by Stamps
这给了我每张“邮票”当天的号码。 例如,如果表是:
S2 | S0 | S0 | S1 | S1 | S3 | S2
结果将是:
S0 : 2,3
S1 : 4,5
S2 : 1,7
S3 : 6
这部分效果很好,但现在我想把这个结果放在表格中
赞Insert Into mytable (S0, S1, S2, S3) = ('2,3','4,5','1,7','6')
但是当我在它之后或之前设置它不起作用。 我该怎么做? 感谢
答案 0 :(得分:1)
我想你想把它转回来。怎么样:
WITH cte AS(
SELECT Stamps, row_number() over (order by (SELECT 1)) rn from week
unpivot
(Stamps FOR Day IN ([Sun], [Mon], [Tue], [Wed], [Thu], [Fri], [Sat]) ) AS unpvt
), cte2 AS (
SELECT Stamps , STUFF((SELECT ','+cast(rn as varchar(9))
from cte where Stamps=A.[Stamps] FOR XML PATH('')), 1 , 1 , '' )
as DayList
from cte A
group by Stamps
)
INSERT MyTable (S0, S1, S2, S3)
select S0, S1, S2, S3 from cte2
PIVOT
(
Max(DayList)
FOR Stamps IN ([S0], [S1], [S2], [S3])
) AS PivotTable;