zoukankan      html  css  js  c++  java
  • T-SQL利用笛卡尔积/窗口函数_分析函数/表连接累计、累加

    T-SQL利用笛卡尔积/窗口函数/表连接累计、累加

    【1】 笛卡尔积与子查询解决累计

    方法1:笛卡尔积

    --原始数据
    
    select templateid,needitem1Count from db_tank..TS_CardMain
    
    --累计数据
    
    select t1.templateId,t1.needitem1Count,sum(t2.needitem1count) sum_num from db_tank..TS_CardMain t1 
    cross join db_tank..TS_CardMain t2 
    where t2.templateid <= t1.templateid
    group by t1.templateid,t1.needitem1Count

    方法2:子查询

    select templateid,needitem1Count, 
    (select sum(needitem1Count) from db_tank..TS_CardMain t2 where t2.templateid<=t1.templateid ) as sum_num
    from db_tank..TS_CardMain t1

    【2】解决分组累加问题:利用表连接、笛卡尔积、子查询

    基于多个分组的分别累加

    方法1:笛卡尔积

    ;with temp1 as (
    select 1 as id ,1 as num
    union all
    select 1 as id ,2 as num
    union all
    select 1 as id ,3 as num
    union all
    select 2 as id ,4 as num
    union all
    select 2 as id ,5 as num
    union all
    select 2 as id ,6 as num
    )
    select  t1.id,t1.num,sum(t2.num) sum_num from temp1 t1  join temp1 t2 on  t2.id =t1.id AND t2.num <= t1.num
    group by t1.id,t1.num
    order by id

      

     解法2:利用子查询

    ;with temp1 as (
    select 1 as id ,1 as num
    union all
    select 1 as id ,2 as num
    union all
    select 1 as id ,3 as num
    union all
    select 2 as id ,4 as num
    union all
    select 2 as id ,5 as num
    union all
    select 2 as id ,6 as num
    )
    select *,(select sum(num) from temp1 where id=t.id and num <= t.num) sum_num from temp1 t

    【3】窗口函数_分析函数(sum over)

    sql server 2012及以上可用 

    rows between unbounded preceding and current row
    --【3.1】利用sum() over()嵌套使用
    ;with temp1 as ( select 1 as id ,1 as num union all select 1 as id ,2 as num union all select 1 as id ,3 as num union all select 2 as id ,4 as num union all select 2 as id ,5 as num union all select 2 as id ,6 as num ) select *,sum(num) over(partition by id order by num asc rows between unbounded preceding and current row) from temp1
      
      
    
    
  • 相关阅读:
    QtDBus快速入门
    论Qt容器与STL
    JS中的!=、== 、!==、===的用法和区别
    JS操作JSON总结
    select2使用方法总结
    Entity Framework插入数据报错:Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
    Windows登录类型及安全日志解析
    <script type="text/html"></script> js模版使用
    在 C# 中,(int) ,Int32.Parse() 和 Convert.toInt32() 三种方法的区别
    关于session,cookie,Cache
  • 原文地址:https://www.cnblogs.com/gered/p/9773566.html
Copyright © 2011-2022 走看看