首页 > 解决方案 > 用值更新列的 SQL 函数

问题描述

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

我有一个输出表,其中包含 2 个变量(附加的 output.csv) 输出表

ID、组、日期

该表有 830 行: 330 有一个“C”组 150 有一个“A”组 50 有一个“B”组

剩下的 300 组为“TEMP”

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

所以表格总计

330 有一个“C”组 250 有一个“A”组 250 有一个“B”组

标签: sqlsql-serversql-function

解决方案


您想要按比例分配“温度”以获得等量的“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 Server 可以很容易地将其放入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;
             

推荐阅读