来自其他表(如分布)的UPDATE表值

时间:2019-10-13 14:41:11

标签: sql sql-server sql-server-2008-r2

我有一个table 1,我必须从其他表table 2分配奖励,但要采用从其他表行起先入先出的方式。

Table 1
ATTIME    | Absent | LeaveType
-----------------------------
2019-01-01| 1      | 
2019-01-02| 1      | 
2019-01-03| 1      | 
2019-01-04| 1      | 
2019-01-05| 1      | 
2019-01-06| 1      | 

Table 2
LeaveType | Total  
-------------------
Casual    | 3   
Sick      | 2

我已经通过使用游标实现了它,但是想要设置基准值 UPDATE QUERY 或其他可以优化我的执行计划的选项

最终结果将是...。

Table 1

ATTIME    | Absent | LeaveType
-----------------------------
2019-01-01| 1      | CL
2019-01-02| 1      | CL
2019-01-03| 1      | CL
2019-01-04| 1      | SL
2019-01-05| 1      | SL
2019-01-06| 1      |

1 个答案:

答案 0 :(得分:0)

在受支持的SQL Server版本中,您将使用累积总和和public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_settings); ArrayList<SettingsTypeModel> list= new ArrayList<>(); list.add(new SettingsTypeModel(SettingsTypeModel.TYPE_SEND_TO_MAIL)); list.add(new SettingsTypeModel(SettingsTypeModel.TYPE_SEND_TO_DRIVE)); SettingsRecyclerAdapter adapter = new SettingsRecyclerAdapter(list,this); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false); RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerVieww); mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); mRecyclerView.setLayoutManager(linearLayoutManager); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mRecyclerView.setClickable(true); mRecyclerView.setAdapter(adapter); } public void onActivityResult(final int requestCode, final int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); } @Override protected void onDestroy() { super.onDestroy(); } @Override public void onBackPressed() { super.onBackPressed(); } }

row_number()

在不受支持的过时SQL Server版本中,累加的总和比较麻烦。一种方法使用相关的子查询:

with toupdate as (
      select t1.*,
             row_number() over (order by attime) as seqnum
      from table1 t1
     )
update toupdate
    set leavetype = t2.leavetype
    from (select t2.*,
                 sum(total) over (order by leavetype) as runningtotal
          from table2 t2
         ) t2
    where toupdate.seqnum between t2.runningtotal + 1 - total and t2.runningtotal;