SQL 用值更新列的函数

SQL Function for updating column with values

那些曾经帮助过我的人,我在日常工作中倾向于大量使用 SAS9.4,但是有时我需要使用 SQL Server

有一个输出 table 我有 2 个变量(附加 output.csv) output table

ID、群组、日期

table 有 830 行: 330有一个“C”组 150人有一个“A”组 50 人有一个“B”组

剩下的 300 人组为“TEMP”

在 SQL 内,我现在不知道如何以编程方式计算出 A+B+C 的总体积。目的是更新“TEMP”列以确保“A”和“B”的数量相等,每个总计 250(总数的剩余部分)

所以 table 总计

330 人有一个“C”组 250人有一个“A”组 250 人属于“B”组

您想按比例分配“温度”以获得等量的“A”和“B”。

所以,我们的想法是将 A、B 和 Temp 中的所有内容加起来,然后除以 2。这就是最终的组大小。然后你可以使用算术将Temp中的行分配给两组:

select t.*,
       (case when seqnum + a_cnt <= final_group_size then 'A' else 'B' end) as allocated_group
from (select t.*, row_number() over (order by newid()) as seqnum
      from t
      where group = 'Temp'
     ) t cross join
     (select (cnt_a + cnt_b + cnt_temp) / 2 as final_group_size,
             g.*
      from (select sum(case when group = 'A' then 1 else 0 end) as cnt_a,
                   sum(case when group = 'B' then 1 else 0 end) as cnt_b,
                   sum(case when group = 'Temp' then 1 else 0 end) as cnt_temp
            from t
           ) g
     ) g

SQL 服务器可以轻松将其放入 update:

with toupdate as (
      select t.*,
             (case when seqnum + a_cnt <= final_group_size then 'A' else 'B' end) as allocated_group
      from (select t.*, row_number() over (order by newid()) as seqnum
            from t
            where group = 'Temp'
           ) t cross join
           (select (cnt_a + cnt_b + cnt_temp) / 2 as final_group_size,
                   g.*
            from (select sum(case when group = 'A' then 1 else 0 end) as cnt_a,
                         sum(case when group = 'B' then 1 else 0 end) as cnt_b,
                         sum(case when group = 'Temp' then 1 else 0 end) as cnt_temp
                  from t
                 ) g
           ) g
      )
update toupdate
    set group = allocated_group;
             

我会采用前 250 名更新样式方法

update top (250) [TableName] set Group = 'A' where exists (Select * from [TableName] t2 where t2.id = [TableName].id order by newid()) and Group = 'Temp'

update top (250) [TableName] set Group = 'B' where exists (Select * from [TableName] t2 where t2.id = [TableName].id order by newid()) and Group = 'Temp'