据我了解,我创建了三个临时表,分别为 ta、tb、tc。
select * into #ta from (
select 'A' a
union all
select 'A' a
union all
select 'A' a
union all
select 'A' a
union all
select 'A' a
union all
select 'A' a
union all
select 'A' a
) a
select * into #tb from (
select 'B' b
union all
select 'B'
union all
select 'B'
union all
select 'B'
union all
select 'B'
) b
select * into #tc from (
select 'C' c
union all
select 'C'
union all
select 'C'
union all
select 'C'
union all
select 'C'
) c
如果表与您的表匹配,则输出类似于 A,A,A,B,B,C,A,A,A,B,B,C,A,B,C,C,C
T-SQL
declare @TAC int = (select count (*) from #ta) -- Table A Count = 7
declare @TBC int = (select count (*) from #tb) -- Table B Count = 5
declare @TAR int = @TAC % 3 -- Table A Reminder = 1
declare @TBR int = @TBC % 2 -- Table B Reminder = 1
declare @TAQ int = (@TAC - @TAR) / 3 -- Table A Quotient = (7 - 1) / 3 = 2, is will passed on NTILE
-- So we gonna split as two group (111), (222)
declare @TBQ int = (@TBC - @TBR) / 2 -- Table B Quotient = (5 - 1) / 2 = 2, is will passed on NTILE
-- So we gonna split as two group (11), (22)
select * from (
select *, NTILE (@TAQ) over ( order by a) FirstOrder, 1 SecondOrder from (
select top (@TAC - @TAR) * from #ta order by a
) ta -- 6 rows are obtained out of 7.
union all
select *, @TAQ + 1, 1 from (
select top (@TAR) * from #ta order by a desc
) ta -- Remaining one row is obtained. Order by desc is must
-- Here FirstOrder is next value of previous value.
union all
select *, NTILE (@TBQ) over ( order by b), 2 from (
select top (@TBC - @TBR) * from #tb order by b
) tb
union all
select *, @TBQ + 1, 2 from (
select top (@TBR) * from #tb order by b desc
) tb
union all
select *, ROW_NUMBER () over (order by c), 3 from #tc
) abc order by FirstOrder, SecondOrder
让我解释一下 T-SQL:
在此之前,FYR:NTILE 和 Row Number
- 获取计数。
- 找到将传递给 NTILE 函数的商。
- 按 NTILE 值和静态排序。
注意:
- 我使用的是 SQL Server 2017。
- 如果 T-SQL 工作正常,那么您需要更改
order by <yourcolumn> 中的列。