TSQL导致特定数量的列

时间:2018-06-30 08:00:58

标签: sql-server tsql transpose

我正在尝试创建一个查询,该查询将按特定列数(例如4)分配行结果。请参见下面的屏幕截图。

enter image description here

1 个答案:

答案 0 :(得分:3)

这是表示问题,应在应用程序级别进行处理。 但是,如果您坚持:

SELECT column1 = MIN(CASE WHEN grp=1 THEN PartNumber+CHAR(13)+SerialNumber END)
      ,column2 = MIN(CASE WHEN grp=2 THEN PartNumber+CHAR(13)+SerialNumber END)
      ,column3 = MIN(CASE WHEN grp=3 THEN PartNumber+CHAR(13)+SerialNumber END)
      ,column4 = MIN(CASE WHEN grp=4 THEN PartNumber+CHAR(13)+SerialNumber END)
FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY rn ORDER BY rn) AS grp
      FROM (SELECT *,(ROW_NUMBER() OVER(ORDER BY 1/0)-1)/4 AS rn FROM tab)s)sub
GROUP BY rn;

DBFiddle Demo