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
      
      
    
    
  • 相关阅读:
    电脑快捷键大全
    js实现页面跳转
    List转换为字符串方法
    Bootstrap4显示和隐藏元素
    反向代理和正向代理区别
    springboot系列一:工作环境无法联网下快速搭建boot项目
    英语故事系列:冠状病毒传播或导致2020首季度全球经济出现萎缩
    BBS网站的制作
    Flask-SQLAlchemy数据库操作
    step-by-step install Nginx反向代理服务器(Ubuntu 18.04 LTS)(转)
  • 原文地址:https://www.cnblogs.com/gered/p/9773566.html
Copyright © 2011-2022 走看看