一个使用FULL JOIN的例子

本文介绍了一种通过SQL查询来分析股票持有者每年新增与退出数量的方法。通过建立测试环境并填充示例数据,展示了如何使用FULL JOIN联合子查询来计算不同股票在各年度的新进持有者及退出持有者的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

--建立测试环境,stock_id 股票代码,hold_year 持有年份,hold_organ 持有者
create table stock(stock_id int,hold_year int,hold_organ int)
insert stock(stock_id,hold_year,hold_organ)
select '001','2006','1001' union all
select '001','2006','1000' union all
select '001','2006','1002' union all
select '001','2007','1002' union all
select '001','2007','1003' union all
select '001','2007','1004' union all
select '002','2006','1001' union all
select '002','2006','1002' union all
select '002','2007','1002' union all
select '002','2007','1003'

--执行测试语句,查询每种股票每年相对于上一年新增的持有者数量和退出的持有者数量
select isnull(_s1.stock_id,_s2.stock_id) as stock_id
 ,isnull(_s1.hold_year,_s2.hold_year+1) as hold_year
 ,count(_s1.stock_id) as 数量
 ,count(_s1.stock_id)-sum(case when _s1.stock_id is not null
  and _s2.stock_id is not null then 1 else 0 end) as 新进数
 ,count(_s2.stock_id)-sum(case when _s1.stock_id is not null
  and _s2.stock_id is not null then 1 else 0 end) as 退出数
from stock _s1
full join stock _s2
 on _s2.stock_id = _s1.stock_id
 and _s2.hold_year = _s1.hold_year-1
 and _s2.hold_organ = _s1.hold_organ
group by isnull(_s1.stock_id,_s2.stock_id),isnull(_s1.hold_year,_s2.hold_year+1)
having isnull(_s1.hold_year,_s2.hold_year+1) <= (select max(hold_year) from stock)
order by isnull(_s1.stock_id,_s2.stock_id),isnull(_s1.hold_year,_s2.hold_year+1)
go
--删除测试环境
drop table stock

/*--测试结果
stock_id    hold_year   数量          新进数         退出数        
----------- ----------- ----------- ----------- -----------
1           2006        3           3           0
1           2007        3           2           2
2           2006        2           2           0
2           2007        2           1           1

(所影响的行数为 4 行)
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值