SQLServer 中一个字段等于1,2,4三个值,怎么查询出同时满足这三个值的记录呢?谢谢了?

如题所述

第1个回答  2011-10-12
不知道你在说什么,不知道是不是这样

同时满足的条件
select * from 表where 表中的字段='1' and 表中的字段='2' and 表中的字段='3'
只需要满足其中的一种
select * from 表where 表中的字段 in(1,2,3)追问

不是满足一个而是全都要满足,他的值有1,2,4;
要求找到有1,2,4 的所有记录 ,必须都要有1,2,4

比如: 电视 状态
海尔 发货
海尔 确认
海尔 收获
只有这三个状态同时满足时,才显示!谢谢了!

追答

1,2,4是分别代表字段中的状态(发货,确认,收获)吗?
还是表示行号的1,2,4?

我猜你说的可以通过group by分组一下就可以实可以得到:
select 电视 ,状态 from a where 状态 in('发货','确认','收获') group by 电视 ,状态

追问

这样我试过,分组有一定的问题!通过状态分组和电视分组得到的数据不一样!我意思能不能这样,通过电视分组,如果状态都满足('发货','确认','收获')则显示!这下说清楚了吧!麻烦你了 啊!

追答

照你那样描述的话应该用不找分组,
select 电视 ,状态 from a where 状态 in('发货','确认','收获')
这样就行了,
真想分组可能还需要别的字段要不然好像不行,至少现在我还没想到可行的

追问

这样不成功!可以试一下!因为电视就这三种状态!用in的话,会查出所有的,是不是啊!我现在要得到的是,同时满足这三个状态的数据!难就难在它只有这三种状态!in里面是or的关系!所以不好用!

追答

你把你的数据和所要得到的数据发给我看下

第2个回答  2011-10-12
假如是stu字段里的A,B,C三种记录
select * from stu where A = '1' or B= '2' or C ='4'
第3个回答  2011-10-12
假如是stu字段里的A,B,C三种记录
select * from stu where A = '1' and B= '2' and C ='4'
第4个回答  2011-10-25
select * from table where a=1 or a=2 or a=3
第5个回答  2011-10-14
select * from tb where 字段 like '%1%' and startdate like '%2%' and startdate like '%4%'追问

这样不行!因为这个字段只包含三个值 1,2,4!麻烦你了!!

追答

select * from tb where 字段 like '%1%' and 字段 like '%2%' and 字段 like '%4%'
这个语句的意思是查询同时包含1 2 4 三个数据的 数据 楼主想要的不是这个?

追问

呵呵是啊!能帮忙吗?谢谢了!

追答

是啊 就是这个语句 三个like前的字段写同一个 字段就行了 楼主试试 看

追问

关键是!这个字段的值只有三个就是1,2,4 这样的话,不就全部查出来了吗??

追答

汗 终于搞懂你的意思了 如下代码你试试看,是不是符合你的要求
create table #tb(aa varchar(10), bb int)
insert into #tb
select 'A',1
union all
select 'B',1
union
select 'A',2
union all
select 'B',2
union all
select 'A',4
union all
select 'C',1
union ALL
select 'C',2
with cte as(
select a.aa, bb=stuff((select ','+cast(bb as varchar(10)) from #tb where aa=a.aa for xml path('')),1,1,'' ) from #tb a
group by a.aa)
select * from cte where bb='1,2,4'

本回答被提问者采纳
相似回答