zoukankan      html  css  js  c++  java
  • 对表中数据逐行累加

    SQL2005 执行脚本
     
     
    --对表中数据逐行累加

    declare  @tempTable table(SID   
    int,  SCORE   int
    insert   @tempTable 
    select   1,                 10   union   all 
    select   2,                 20   union   all 
    select   3,                 30   union   all 
    select   4,                 40   union   all 
    select   5,                 50   
    --查看添加的数据
    select * from @tempTable
    drop table temptable
    select * into tempTable from @tempTable
    --=====================================================
    --1.使用子查询来计算累加和(非常好的一个方法)
    --=====================================================

    SELECT 
    TB1.SID, 
    SUM(TB2.SCORE) SCORE 
    FROM 
    tempTable TB1, (
    SELECT SID, SCORE 
                    FROM TempTable 
                    )TB2 
    WHERE 
    TB1.SID 
    >= TB2.SID 
    GROUP BY TB1.SID 

    --======================================
    SELECT SID,
    SUM(SCORE) 
    AS SCORE,
             ( 
                
    SELECT SUM(SCORE)
                FROM TempTable
                WHERE (SID 
    <= A.SID)
            )
            
    AS [SUM_SCORE]
    FROM TempTable 
    AS A
    GROUP BY SID
    ORDER BY SID


    --======================================
    --2.通过更新的方法实现
    --======================================
    --声明变量 
    declare   @num   
    int,@SID   int 
    set   @num   =   0 
    --开始更新,注意SQL执行更新时,是一行行更新数据.
    update   @tempTable   
    set   @num   =   case   when   @SID   <=   SID   then     @num   +   SCORE   else   SCORE   end
          @SID   
    =   SID, 
          SCORE   
    =   @num 
    --查看更新后的结果
    select   *   from   @tempTable 

    --===========注意应用此方法时,SID是有序存储的===================


    --======================================
    --3.通过查询的方法实现
    --======================================
    select 
    sum (
    case  when sid<=1 then score endas S1,
    sum (
    case  when sid<=2 then score endas S2,
    sum (
    case  when sid<=3 then score endas S3,
    sum (
    case  when sid<=4 then score endas S4,
    sum (
    case  when sid<=5 then score endas S5
    from tempTable

    --===========注意应用此方法时,SID数量是已知,但可以是无序存储的=============




     
     
  • 相关阅读:
    Servlet第六篇【Session介绍、API、生命周期、应用、与Cookie区别】
    Servlet第五篇【介绍会话技术、Cookie的API、详解、应用】
    Servlet第四篇【request对象常用方法、应用】
    Servlet第三篇【request和response简介、response的常见应用】
    Tomcat就是这么简单
    JProfiler远程监控Linux上Tomcat的安装过程细讲(步骤非常详细!!!)
    FileChannel类的理解和使用
    Lifetime-Based Memory Management for Distributed Data Processing Systems
    Spark的核心RDD(Resilient Distributed Datasets弹性分布式数据集)
    Hadoop与Spark之间的比较
  • 原文地址:https://www.cnblogs.com/furenjun/p/oneRowByOneRowAdd.html
Copyright © 2011-2022 走看看