SQL Server 2016-五列到单行

时间:2018-12-10 23:23:47

标签: sql sql-server tsql sql-server-2016

我有以下数据

+--------+
| orders |
+--------+
| S1     |
| S2     |
| S3     |
| S4     |
| S5     |
| S6     |
| S7     |
| S8     |
| S9     |
| S10    |
| S11    |
| S12    |
+--------+

我需要按以下方式返回结果-在一列中容纳五行:

+-----------------+
|     Orders      |
+-----------------+
| S1,S2,S3,S4,S5  |
| S6,S7,S8,S9,S10 |
| S11,S12         |
+-----------------+

没有什么可分组或将它们分成几行的。所以我分配了一个row_number,并在row_number上做了mod 5。几乎可以,但是效果不佳。

这是我尝试过的:

;with mycte as (
select
'S1' as orders
union all select
'S2'
union all select
'S3'
union all select
'S4'
union all select
'S5'
union all select
'S6'
union all select
'S7'
union all select
'S8'
union all select
'S9'
union all select
'S10'
union all select
'S11'
union all select
'S12'
)
,mycte2 as (
Select 
orders
,ROW_NUMBER() over( order by orders) %5 as rownum 
from mycte
)
select distinct
 STUFF((
            SELECT ',' + mycte2.orders
            FROM mycte2
            where t1.rownum= mycte2.rownum
            FOR XML PATH('')
            ), 1, 1, '') orders 
, rownum
 from mycte2 t1

结果是:

+-----------+--------+
|  orders   | rownum |
+-----------+--------+
| S1,S3,S8  |      1 |
| S10,S4,S9 |      2 |
| S11,S5    |      3 |
| S12,S6    |      4 |
| S2,S7     |      0 |
+-----------+--------+

有人可以告诉我如何达到我想要的结果吗?

1 个答案:

答案 0 :(得分:4)

怎么样

CREATE TABLE T
    ([orders] varchar(3));

INSERT INTO T
    ([orders])
VALUES
    ('S1'),
    ('S2'),
    ('S3'),
    ('S4'),
    ('S5'),
    ('S6'),
    ('S7'),
    ('S8'),
    ('S9'),
    ('S10'),
    ('S11'),
    ('S12');

WITH CTE AS
(
  SELECT Orders,
        (ROW_NUMBER() OVER(ORDER BY LEN(Orders)) - 1) / 5 RN
  FROM T
)
SELECT STRING_AGG(Orders, ',')
FROM CTE
GROUP BY RN
ORDER BY RN;

OR

SELECT STUFF(
              (
                SELECT ',' + Orders
                FROM CTE
                WHERE RN = TT.RN
                FOR XML PATH('')
              ), 1, 1, ''
            ) Orders
FROM CTE TT
GROUP BY RN
ORDER BY RN;
  

您可以使用(SELECT 1)代替LEN(Orders)

返回:

+-----------------+
|     Orders      |
+-----------------+
| S1,S2,S3,S4,S5  |
| S6,S7,S8,S9,S10 |
| S11,S12         |
+-----------------+

Demo