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

被折叠的 条评论
为什么被折叠?



