题目:假如有一表如下所示tb:
product month number
aa 2 30
aa 3 60
bb 2 30
bb 3 30
需要查找出number不相同的2,3月份的记录,查询的记录为:
product month number
aa 2 30
aa 3 60
答案:
(1)
select a.* from tb a join tb b on a.product=b.product and a.number<>b.number and a.month in(2,3)
(2)
create table #tb
(
product varchar(10),
[month] int,
number int
)
insert into #tb select 'aa',2,30
union all select 'aa',3,60
union all select 'bb',2,30
union all select 'bb',3,30
select * from #tb t where exists (select * from tb where t.product=product and number<>t.number) and [month] in(2,3)