论坛首页 综合技术论坛

考考你的SQL水平

浏览 57277 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (13) :: 隐藏帖 (1)
作者 正文
   发表时间:2012-04-25  
select * from
(select * from test where hobby = 'basketball') as a join
(select * from test where hobby = 'badminton') as b
on a.name = b.name
0 请登录后投票
   发表时间:2012-04-26   最后修改:2012-04-26
select * from (
select name,
cont=sum(case  when hobby='basketball' or hobby='badminton' then 1 else 0 end)
from test  group by name
)t where t.cont>1  这才是正解
0 请登录后投票
   发表时间:2012-04-26  
select NAME from (select * from test where hobby in ('basketball','badminton')) group by name having count(*)>1
0 请登录后投票
   发表时间:2012-04-26  
select
distinct t1.*
from test t1
inner join test t2 on t1.name = t2.name and t2.hobby in ('basketball','badminton')
inner join test t3 on t2.name = t3.name and t3.hobby in ('basketball','badminton')
where t2.hobby !=t3.hobby


select t4.*
from test t4
where exists (select 1 from test t2 
inner join test t3 on t2.name = t3.name and t3.hobby in ('basketball','badminton')
where t2.hobby !=t3.hobby and t2.hobby in ('basketball','badminton') and t2.name=t4.name)

0 请登录后投票
   发表时间:2012-04-27  
HAVING COUNT 扩展起来比较方便 
0 请登录后投票
   发表时间:2012-04-28  
select * from test t
where
exists(select 'z' from test z where z.name=t.name and t.hobby<>z.hobby and z.hobby in('basketball','badminton'))
and t.hobby in('basketball','badminton')
0 请登录后投票
   发表时间:2012-04-28  
select t1.* from test t1, test t2 where t1.name=t2.name
and(
t1.hobby='basketball' and t2.hobby='badminton' or
t2.hobby='basketball' and t1.hobby='badminton'
)order by t1.name, t1.hobby
0 请登录后投票
   发表时间:2012-04-28  
如果第9行也想返回:

select t0.* from test t0, test t1, test t2
where t0.name=t1.name and t1.name=t2.name
and t1.hobby='basketball' and t2.hobby='badminton'
order by t0.name, t0.hobby
0 请登录后投票
   发表时间:2012-04-28  
select name from test where HOBBY in ('basketball','badminton')
group by name having count(1)>1
前提条件是没重复数据
0 请登录后投票
   发表时间:2012-04-28   最后修改:2012-04-28
select name
from testbb a
where hobby = 'basketball'
and exists (
select 1
from testbb b
where a.name = b.name
and b.hobby = 'badminton'
)

=====================
倒,发了才发现跟楼上一哥们的一样,惭愧了。
0 请登录后投票
论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics