以前幫助過我的人,我在日常作業中經常使用SAS9.4,但有時我需要使用SQL Server
我有一個輸出表,有2個變數(附輸出.cv)。
我有一個帶有2個變數的輸出表(附上output.csv)。 輸出表
ID, GROUP, DATE
該表有 830 行。 330條有一個 "C "組 150條有一個 "A "組 50條有一個 "B "組
剩下的300條組為 "TEMP"在SQL中,我現在不知道如何通程序式計算出A B C的總數量。我們的目的是更新 "TEMP "列,以確保 "A "和 "B "的數量相等,各為250個(總計數的其余部分)因此,表的總數為
因此,該表的總數
330人有一個 "C "組 250人有一個 "A "組 250人有一個 "B "組
uj5u.com熱心網友回復:
你想使 "temp "成比例,以獲得等量的 "A "和 "B"。
因此,我們的想法是把A、B和Temp中的所有東西都算出來,然后除以2,這就是最終的組別大小。 然后你可以使用算術將Temp中的行分配給兩個組:
select t.*,
(case when seqnum a_cnt < = final_group_size then 'A'/span> else 'B'/span> end) as allocated_group
from (select t. *, row_number() over (orderby 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'/span> else 'B'/span> end) as allocated_group
from (select t. *, row_number() over (orderby 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。
uj5u.com熱心網友回復:
我會采用top 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'/span> where exists (Select * from [TableName] t2 where t2. id = [TableName].id order by newid() ) and Group = 'Temp'
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/307260.html
標籤:
上一篇:KeyError:'IDENTITY_ENDPOINT'在Azure環境中的錯誤
下一篇:t-sql重復組內的行數
