利用游标,检索哪些客户2019年连续六个月以上没有购买过“百威啤酒”这个商品

利用游标,检索哪些客户2019年连续六个月以上没有购买过“百威啤酒”这个商品

数据库游标实际上是一种能从包含多条记录的结果集中每次只提取一条记录的程序机制。游标提供了在结果集一次一行或者多行向前或向后浏览数据的能力。

在本实例中,可检索出每个客户哪些月没有购买过“百威啤酒”这个商品并创建一个表,并以该表作为游标指针的表,依次每个客户向下判断月份是否相差一个月份。

(MySQL8.0版本)

(1)

drop table if exists pp;
create table pp select distinct customerid,month(orderdate)as month,
productname from orders join orderitems using(orderid)
join products using(productid) where year(orderdate)=2019 and productname='百威啤酒'
order by customerid,month;

第一步先创建一个表(也可使用衍生表with cte as)检索出每个客户哪些月购买过"百威啤酒",执行该条语句得(select * from pp):

(2)

drop table if exists tt;
create table tt select distinct customerid, month(orderdate)as xmonth from orders
a where month(orderdate) not in(select month from pp b where
a.customerid=b.customerid)order by customerid,month(orderdate);
select * from tt;

第二步创建一个表(tt)包含每个客户哪些月没有购买过“百威啤酒”这个商品,使用 not in 语句,执行该条语句(select * from tt)得:

(3)

drop procedure if exists sp1;
delimiter $$
create procedure sp1()
begin
declare $cid,$cid1 varchar(100);
declare $xmonth,$xmonth1,$n int default 0;
declare $flag boolean default 1;
declare cur1 cursor for select customerid,xmonth from tt;
declare continue handler for not found set $flag=0;
drop temporary table if exists cc;
create temporary table cc(customerid varchar(100));
open cur1;
fetch cur1 into $cid,$xmonth;
set $cid1=$cid,$xmonth1=$xmonth,$n=0;
while($flag=1)do
if($cid=$cid1)then
if($xmonth=$xmonth1+1)then set $n=$n+1;
else set $n=0;
end if;
else
set $n=0;
end if;
if($n>=6)then
insert into cc values($cid);
end if;
set $cid1=$cid,$xmonth1=$xmonth;
fetch cur1 into $cid,$xmonth;
end while;
close cur1;
end$$
delimiter ;
call sp1();
select distinct customerid from cc;

第三步,利用游标,检索出哪些客户不符合条件,在这里我们创建存储过程sp1,并创建一个临时表cc,游标判断过程中如若有不符合条件的客户便将该客户的编码插入该表中,

得到以下客户共64条记录:

 

代码及解题思路若有问题欢迎指正交流,谢谢!

 

 

 

 

 

 

 

 

 

posted @ 2021-05-28 17:08  旺旺哈  阅读(200)  评论(0)    收藏  举报