此处用到了Pivoting技术
注:Pivoting技术是指一种可以把行转换为列的技术,在Pivoting的执行过程中可能会用到聚合。
这里讨论的都是静态Pivoting查询,即用户需要提前知道旋转的属性列的值,对于动态Pivoting,需要动态地构造查询字符串。
关系除法问题的解决方案:
(当除数集合中的元素数量较小时,Pivoting可以用于解决关系除法问题)
-
create table devision(
-
orderid varchar(10) not null,
-
productid int not null,
-
primary key(orderid,productid));
-
insert into devision select 'A',1;
-
insert into devision select 'A',2;
-
insert into devision select 'A',3;
-
insert into devision select 'A',4;
-
insert into devision select 'B',2;
-
insert into devision select 'B',3;
-
insert into devision select 'B',4;
-
insert into devision select 'C',3;
-
insert into devision select 'C',4;
-
insert into devision select 'D',4;
解释一下:
表devision存储订单中包含的产品,比如A订单所包含的产品ID为1、2、3、4,C订单所包含的产品ID为3、4,以此类推
Pivoting技术可以把每个订单中的产品旋转到单独的列之中。
比如需要查询productid为2、3、4的订单,可以采用以下方法:
-
select orderid
-
from(select orderid,
-
max(case when productid=2 then 1 end) as p2,
-
max(case when productid=3 then 1 end) as p3,
-
max(case when productid=4 then 1 end) as p4
-
from devision
-
group by orderid
-
) p
-
where p2=1 and p3=1 and p4=1;
得到的结果很显然:
因为只有A和B订单包含产品ID为2、3、4的产品
上sql语句中的派生表P输出结果为:
如果将生成派生表p的语句中的max函数改成count函数,则更加直观:
及若产品存在则返回为1,不存在则返回为0,而不是null。
-
-
select orderid
-
from(select orderid,
-
count(case when productid=2 then 1 end) as p2,
-
count(case when productid=3 then 1 end) as p3,
-
count(case when productid=4 then 1 end) as p4
-
from devision
-
group by orderid
-
) p
-
where p2=1 and p3=1 and p4=1;
-
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29773961/viewspace-1255297/
,如需转载,请注明出处,否则将追究法律责任。