日期:2014-05-17  浏览次数:20766 次

求分类查询的一个sql
我需求是这样的.

表A:
字段
  userid sex(性别)
  1 1
  2 2
  3 1
   
表B
字段
  userid rank(排名)
  1 3
  2 1
  3 2



我想查的男女各第一名的userid.
sql 不好,求助大家

------解决方案--------------------
SQL code
select top 1 userid
from A inner join B on A.userid=B.userid
where sex=1
order by rank
union all
select top 1 userid
from A inner join B on A.userid=B.userid
where sex=2
order by rank

------解决方案--------------------

select userid from b
(
select sex,min(rank) as rank from 
(
select * from a , b
where a.userid=b.userid
) c
group by sex
) d
where b.rank =d.rank