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

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

【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】表连接与笛卡尔积

  基于多个分组的分别累加

;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】窗口函数_分析函数

--【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
  
  

 

 
 

 

转载于:https://www.cnblogs.com/gered/p/9773566.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值