【SQL】行转列过滤,使用别名和不使用别名的区别用法。

需求为:

仿太平洋网站筛选。

多选类型的字段应采用‘并且’;单选和录入类型的字段应采用‘或者’

比如有如下选项:

参数头 参数体
操作系统(多选) win7 win8
运行内存(单选) 2G 4G

 

 

 

 

商品库存在有3个商品,分别为:

lenovoB111,操作系统:win7、win8,运行内存:2G

lenovoB222,操作系统:win7、win8,运行内存:4G

lenovoB333:操作系统:win10,运行内存4G

那这个时候,我吧上面的选项win7、win8、2G、4G全部勾选后,点击商品筛选按钮,生成的筛选条件应该为:

win7、win8、2G

win7、win8、4G

符合这两个筛选条件的商品将会给筛选出来,即(lenovo111&lenovo222这两台电脑)

 

简洁表结构为:

参数头:

id name type

 

参数体:

id name titleId

 

商品参数组成:

id product_id param_item_id

 

 

模拟参数组成记录(省略id):

(标识下以上商品对应属性id

商品:

电脑的对应id号:lenovo111:1,lenovo222:2,lenovo333:3

参数:

操作系统对应id:win7:1,win8:2,win10:3

内存对应id:2G:4,4G:5

product_id product_param_item_id
1 1
1 2
1 4
2 1
2 2
2 5
3 3
3 5

 

 

 

 

 

 

通过预想最后结果应该为1、2

 

查询语句(使用列转行,使结果变成以下):

product_id product_param_item_id
1 1,2,4
2 1,2,5
3 3,5

 

 

 

--因为t.c不可以用,所以使用子查询

select t2.product_id,t2.c from (
select t.product_id,to_char(wmsys.wm_concat(t.product_param_item_id)) c from T_EB_PRODUCT_PARAM_COMPOSE t
group by t.product_id) t2
where 1=1 and
(',' || t2.c || ',' like '%,1,%') and
(',' || t2.c || ',' like '%,2,%') and

(',' || t2.c || ',' like '%,4,%')
or
(',' || t2.c || ',' like '%,1,%') and
(',' || t2.c || ',' like '%,2,%') and

(',' || t2.c || ',' like '%,5,%');

--直接使用having过滤
select t.product_id from T_EB_PRODUCT_PARAM_COMPOSE t
group by t.product_id
having 1=1 and
(',' || t2.c || ',' like '%,1,%') and
(',' || t2.c || ',' like '%,2,%') and

(',' || t2.c || ',' like '%,4,%')
or
(',' || t2.c || ',' like '%,1,%') and
(',' || t2.c || ',' like '%,2,%') and

(',' || t2.c || ',' like '%,5,%');

posted @ 2015-03-20 16:18  tidyko  阅读(899)  评论(0编辑  收藏  举报