我有一个表(Microsoft SQL Server 2012),我需要通过col1在报表中进行分组,但包括由col2顺序确定的中断(在此简化示例中)。
col1 col2
A 1
A 2
A 3
B 4
A 5
C 6
按col1分组给了我3组(A,B,C),但我需要A:1,2,3与A:5分开,在上面的例子中给我4组:
A: 1,2,3
B: 4
A: 5
C: 6
我试过了
SELECT row_number() OVER (PARTITION BY col1 order by col2) as GroupNumber, col1, col2
FROM MyTable
但这只是给了我每组中的序列号。我真正想要的是为每个小组编号的某种方式,但我很好并且真的卡住了!
为了澄清,我希望得到类似于以下内容的结果: -
grp col1 col2
1 A 1
1 A 2
1 A 3
2 B 4
3 A 5
4 C 6
答案 0 :(得分:3)
使用ROW_NUMBER
:
;WITH Cte AS(
SELECT *,
grp = col2 - ROW_NUMBER() OVER(PARTITION BY col1 ORDER BY col2)
FROM MyTable
)
SELECT * FROM Cte ORDER BY col1, col2
为了您想要的结果:
;WITH Cte AS(
SELECT *,
grp = col2 - ROW_NUMBER() OVER(PARTITION BY col1 ORDER BY col2)
FROM MyTable
)
SELECT
c.col1,
x.col2
FROM Cte c
CROSS APPLY (
SELECT STUFF((
SELECT ',' + CONVERT(VARCHAR(10), col2)
FROM Cte
WHERE
col1 = c.col1
AND grp = c.grp
ORDER BY col2
FOR XML PATH('')
), 1, 1,'')
) x(col2)
GROUP BY c.col1, c.grp, x.col2
答案 1 :(得分:0)
declare @tb as table (col1 nvarchar(5), col2 int);
insert into @tb values ('A',1)
insert into @tb values ('A',2)
insert into @tb values ('A',3)
insert into @tb values ('B',4)
insert into @tb values ('A',5)
insert into @tb values ('C',6)
select grp.grpNo,org.col1,org.col2 from @tb org
inner join (select row_number() over (order by t1.col1) as grpNo, t1.col1 from
(select col1 from @tb group by col1) t1) grp on org.col1 = grp.col1 order by grp.grpNo