62,266
社区成员
发帖
与我相关
我的任务
分享
--> 测试数据:[TableA]
if object_id('[TableA]') is not null drop table [TableA]
create table [TableA]([id] int,[value] int)
insert [TableA]
select 1,25 union all
select 2,15 union all
select 3,10 union all
select 4,3 union all
select 5,1 union all
select 6,5 union all
select 7,14 union all
select 8,16 union all
select 9,5 union all
select 10,7
select m_id=case when flag=0 then 'A' when flag=1 then 'B' when flag=2 then 'C' end,m_value=sum(value)from (
select *,flag=(Row_Number() over(order by newid())-1)%(select count(1)/3 from [TableA]) from [TableA]
)t
group by flag
/*
m_id m_value
---- -----------
A 33
B 28
C 40
(3 行受影响)
*/
drop table [TableA]
--> 测试数据:[TableA]
if object_id('[TableA]') is not null drop table [TableA]
create table [TableA]([id] int,[value] int)
insert [TableA]
select 1,25 union all
select 2,15 union all
select 3,10 union all
select 4,3 union all
select 5,1 union all
select 6,5 union all
select 7,14 union all
select 8,16 union all
select 9,5 union all
select 10,6
select flag,sum(value)from (
select *,flag=(id-1)/(select count(1)/3 from [TableA]) from [TableA]
)t
group by flag
/*
flag
----------- -----------
0 50
1 9
2 35
3 6
(4 行受影响)
*/
drop table [TableA]