0

我有这个 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')

但是当我在它之后或之前设置它不起作用。我该怎么做?谢谢

4

1 回答 1

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;

SQL小提琴:http ://sqlfiddle.com/#!6/37ff8/2

于 2013-10-16T06:17:59.053 回答