一个数据库查询的问题 请高手帮忙啊~~~
现在有表A和表B
表A
userid username
1 张三
2 李四
表B
userid userlevel
1 1
1 2
1 3
2 1
2 2
现在要用一条sql查询 或者用视图搞定表搞定表A中userid 在表B中userlevel最高的一条 然后输出userid username和usertoplevel.
userid username usertoplevel
1 张三 3
2 李四 2
------解决方案----------------------原始数据:@A
declare @A table(userid int,username varchar(5))
insert @A
select 1, '张三 ' union all
select 2, '李四 '
--原始数据:@B
declare @B table(userid int,userlevel int)
insert @B
select 1,1 union all
select 1,2 union all
select 1,3 union all
select 2,1 union all
select 2,2
select a.*,usertoplevel=max(b.userlevel) from @A a join @B b on a.userid=b.userid group by a.userid,username order by a.userid
/*
userid username usertoplevel
1 张三 3
2 李四 2
*/
------解决方案--------------------create table a(userid int,username varchar(10))
insert into a values(1, '张三 ')
insert into a values(2, '李四 ')
create table b(userid int,userlevel int)
insert into b values(1, 1)
insert into b values(1, 2)
insert into b values(1, 3)
insert into b values(2, 1)
insert into b values(2, 2)
go
select a.* , t.usertoplevel from a,
(select userid,max(userlevel) usertoplevel from b group by userid) t
where a.userid = t.userid
/*
userid username usertoplevel
----------- ---------- ------------
1 张三 3
2 李四 2
(所影响的行数为 2 行)
*/
select a.* , max(userlevel) usertoplevel from a,b
where a.userid = b.userid
group by a.userid,a.username
order by a.userid
/*
userid username usertoplevel
----------- ---------- ------------
1 张三 3
2 李四 2
(所影响的行数为 2 行)
*/
drop table a,b