SQL Server 2012从三个生成多个列取决于序列号

时间:2018-02-03 14:59:53

标签: sql-server

SQL Server 2012:我有一个包含3列和30行的表,如第一个屏幕截图所示:

first image

我需要将序列号10之后的行分成另一列,如第二个屏幕截图所示:

Second image

1 个答案:

答案 0 :(得分:1)

我会使用子查询和连接来执行此操作:

SELECT sub.*,
sub2.SN1 AS SN2, sub2.MPType1 AS MPType2, sub2.MPTrade1 AS MPTrade2,
sub3.SN1 AS SN3, sub3.MPType1 AS MPType3, sub3.MPTrade1 AS MPTrade3
FROM
(SELECT *
 FROM t
 WHERE SN1 < 11) sub
INNER JOIN
(SELECT *
 FROM t
 WHERE SN1 BETWEEN 11 AND 20) sub2
ON sub.SN1 + 10 = sub2.SN1
INNER JOIN
(SELECT *
 FROM t
 WHERE SN1 > 20) sub3
ON sub2.SN1 + 10 = sub3.SN1