我想得到这样的输出,有人可以帮我逻辑吗

时间:2019-01-29 05:32:59

标签: sql sql-server

输入

id  nm
1   A
2   B
3   C
4   D
5   E
6   F
7   G
8   H
9   I
10  J
11  K
12  L
13  M
14  N
15  O
16  P


output          
A   B   C   D
E   F   G   H
I   J   K   L
M   N   O   P

这是输入,我想要这样的输出

1 个答案:

答案 0 :(得分:5)

您可以使用MOD (%)并像下面这样应用PIVOT来轻松实现这一目标。

;with cte as
(
  select *, id%4 m from @table
)
select [1], [2], [3], [0] AS [4]
from 
(
  select ROW_NUMBER() OVER(PARTITION BY M ORDER BY ID) RN , M, NM
  from CTE
) src
pivot
(
  MAX(NM)
  for M in ([1], [2], [3],[0])
) piv;

完整代码:

declare @table table (id int,  nm char)
insert into @table values
( 1,  'A'),(2,  'B'),(3,  'C'),(4,  'D'),(5,  'E'),(6 , 'F'),(7,  'G'),(8,  'H'),
(9 , 'I'),(10 ,'J'),(11, 'K'),(12, 'L'),(13, 'M'),(14 ,'N'),(15, 'O'),(16, 'P')

;with cte as
(
  select *, id%4 m from @table
)

select [1], [2], [3],[0] AS [4]
from 
(
  select ROW_NUMBER() OVER(PARTITION BY M ORDER BY ID) RN , M, NM
  from CTE
) src
pivot
(
  MAX(NM)
  for M in ([1], [2], [3],[0])
) piv;

输出:

+---+---+---+---+
| 1 | 2 | 3 | 4 |
+---+---+---+---+
| A | B | C | D |
+---+---+---+---+
| E | F | G | H |
+---+---+---+---+
| I | J | K | L |
+---+---+---+---+
| M | N | O | P |
+---+---+---+---+

在线演示:

Here