针对如下表格:
代码 值 单号
a 12 1
b 100 1
a 96 1
d 11 2
b 10 2
a 5 2现在我要得到:在单号基础上:(代码是a并且值>10)并且(代码是b并且值>30)所有记录
这样说清楚不,我在描述下
譬如针对单号1的我要查询:单号=1 并且(代码是a并且值>10)并且(代码是b并且值>30)
其中这个1是不确定的,就是所有的
代码 值 单号
a 12 1
b 100 1
a 96 1
d 11 2
b 10 2
a 5 2现在我要得到:在单号基础上:(代码是a并且值>10)并且(代码是b并且值>30)所有记录
这样说清楚不,我在描述下
譬如针对单号1的我要查询:单号=1 并且(代码是a并且值>10)并且(代码是b并且值>30)
其中这个1是不确定的,就是所有的
这个可以的,优化一下吧
union
select 单号 from table1 where 代码='b' and 值>30
不知道这是不是你想要的结果?
(
code varchar(5),
num int,
id int
)
insert into #t
select 'a',12,1 union all
select 'b',100,1 union all
select 'a',96,1 union all
select 'd',111,2 union all
select 'b',10,2 union all
select 'a',5,2 union all
select 'a',23,3 union all
select 'b',50,3 union all
select 'a',3,4 union all
select 'b',100,4
SELECT id
FROM #t a
WHERE (SELECT COUNT(CASE WHEN code = 'a' AND num > 10 THEN id END)
FROM #t b
WHERE b.id = a.id) > 0 AND
(SELECT COUNT(CASE WHEN code = 'b' AND num > 30 THEN id END)
FROM #t b
WHERE b.id = a.id) > 0
GROUP BY id--结果
1
3看是不是你所要的。
select * from tab
where (case when code = 'a' and num > 10 then 1
when code = 'b' and num > 30 then 1
else 0 end) = 1
and id = @id
select *from (
select *from #t
where code='a' and num>10
union all
select *from #t
where code='b' and num>30) a
where id=1
这个怎么理解呀
============
@id是变量啊 就是你的1 啊上面的
也就是条件限制
and id = @id 去掉就可以了你的意思1是变的 所以用了变量啊
条件1:(代码是a并且值>10)
条件2:(代码是b并且值>30)
比较着俩条件的前提是相同id的基础上作比较,
id不相同的就不符合记录了
from 表名 a
where 代码='a'
and 值>10
and exists (
select 1 from 表名
where 代码='b'
and 值>30
and 单号=a.单号
)
(
CODE varchar(5),
VAL int,
BILL int
)
insert into @t
select 'a',12,1 union all
select 'b',100,1 union all
select 'a',96,1 union all
select 'd',111,2 union all
select 'b',10,2 union all
select 'a',5,2 union all
select 'a',23,3 union all
select 'b',50,3 union all
select 'a',3,4 union all
select 'b',100,4
SELECT DISTINCT B.BILL
FROM (SELECT BILL FROM @T WHERE CODE = 'A' AND VAL > 10) A
JOIN (SELECT BILL FROM @T WHERE CODE = 'B' AND VAL > 30) B
ON A.BILL=B.BILL