日期:2014-05-18  浏览次数:20743 次

求sql 语句一条
SQL code


create table [tb]([商品名] varchar(43),[特性名] varchar(30),[特性值] varchar(40) ,
CONSTRAINT [PK_SM_KeyValue] PRIMARY KEY  NONCLUSTERED 
    (
        [商品名] ,[特性名]
    )  ON [PRIMARY]   )

insert [tb]
select '金士顿内存re5211' ,'大小' ,'1g'  union all
select '金士顿内存re5211' ,'品牌' ,'金士顿'  union all
select '金士顿内存re5211' ,'类型' ,'服务器内存'  union all

select '金士顿内存te5311' ,'大小' ,'4g'  union all
select '金士顿内存te5311' ,'品牌' ,'金士顿'  union all
select '金士顿内存te5311' ,'类型' ,'笔记本内存'  union all

select 'sandisk内存te5311' ,'大小' ,'4g'  union all
select 'sandisk内存te5311' ,'品牌' ,'sandisk'  union all
select 'sandisk内存te5311' ,'类型' ,'笔记本内存'  union all

select 'pentium cpu e2500' ,'主频' ,'2.18'  union all
select 'pentium cpu e2500' ,'接口' ,'socket 744'  union all

select 'pentium cpu T2500' ,'主频' ,'2.38'  union all
select 'pentium cpu T2500' ,'接口' ,'socket 744'  


查询大小是4g的内存

查询大小是4g ,品牌是 sandisk的内存



------解决方案--------------------
SQL code

select  * from tb where  [特性值]='4g' and  charindex('sandisk',[商品名])<>0

------解决方案--------------------
SQL code
select  * from tb where [特性名]='大小' AND  [特性值]='4g'

------解决方案--------------------
SQL code

--查询大小是4g的内存
SELECT [商品名]
FROM tb
WHERE [特性名] = '大小' AND [特性值] = '4G'
--查询大小是4g ,品牌是 sandisk的内存
SELECT [商品名]
FROM tb
WHERE [特性名] = '大小' AND [特性值] = '4G'
INTERSECT
SELECT [商品名]
FROM tb
WHERE [特性名] = '品牌' AND [特性值] = 'sandisk'

------解决方案--------------------
SQL code

create table [tb]([商品名] varchar(43),[特性名] varchar(30),[特性值] varchar(40) ,
CONSTRAINT [PK_SM_KeyValue] PRIMARY KEY  NONCLUSTERED 
    (
        [商品名] ,[特性名]
    )  ON [PRIMARY]   )

insert [tb]
select '金士顿内存re5211' ,'大小' ,'1g'  union all
select '金士顿内存re5211' ,'品牌' ,'金士顿'  union all
select '金士顿内存re5211' ,'类型' ,'服务器内存'  union all

select '金士顿内存te5311' ,'大小' ,'4g'  union all
select '金士顿内存te5311' ,'品牌' ,'金士顿'  union all
select '金士顿内存te5311' ,'类型' ,'笔记本内存'  union all

select 'sandisk内存te5311' ,'大小' ,'4g'  union all
select 'sandisk内存te5311' ,'品牌' ,'sandisk'  union all
select 'sandisk内存te5311' ,'类型' ,'笔记本内存'  union all

select 'pentium cpu e2500' ,'主频' ,'2.18'  union all
select 'pentium cpu e2500' ,'接口' ,'socket 744'  union all

select 'pentium cpu T2500' ,'主频' ,'2.38'  union all
select 'pentium cpu T2500' ,'接口' ,'socket 744'  


--1
select * from tb where [特性名]='大小' and [特性值]='4g'
--2

select * from tb where [特性名]='大小' and [特性值]='4g'
and [商品名]=(select [商品名] from tb where [特性名]='品牌' and [特性值]='sandisk')

------解决方案--------------------
说明一下:

1. 提取所有满足任意条件的数据
SQL code
insert into @result
select a.*
from [tb] a
join @filter b on 1=1
    and a.特性名 = b.特性名
    and a.特性值 = b.特性值