固定行数

时间:2017-06-27 17:08:43

标签: sql-server tsql

想要将结果集分成n个组(例如2个):

当前结果集:

ColA, ColB 100, A 100, B 100, C 100, D 101, E 101, F 101, G 101, H 101, I

具有基于唯一ColA的分区的当前查询:

100, "A,B,C,D" 101, "E,F,G,H,I"

但是,我想将分区限制为不超过2:

PartitionId, ColA, ColB 1, 100, A 1, 100, B 2, 100, C 2, 100, D 1, 101, E 1, 101, F 2, 101, G 2, 101, H 3, 101, I

然后我可以通过前两列的组合进行分区来生成:

1, 100, "A,B" 2, 100, "C,D" 1, 101, "E,F" 2, 101, "G,H" 3, 101, "I"

1 个答案:

答案 0 :(得分:1)

使用common table expression row_number()(加1,除以2)和stuff() with select ... for xml path ('') method of string concatenation

;with cte as (
select *
  , grp = (row_number() over (partition by colA order by colB)+1)/2
from t
)
select 
    grp
  , ColA
  , ColB = stuff((
      select ','+ColB
      from cte i
      where cte.ColA = i.ColA
        and cte.grp = i.grp
      for xml path (''), type).value('(./text())[1]','nvarchar(max)')
      ,1,1,'')
from cte
group by colA, grp
order by colA, grp

rextester演示:http://rextester.com/DUCRPN45791

返回:

+-----+------+------+
| grp | ColA | ColB |
+-----+------+------+
|   1 |  100 | A,B  |
|   2 |  100 | C,D  |
|   1 |  101 | E,F  |
|   2 |  101 | G,H  |
|   3 |  101 | I    |
+-----+------+------+