/*
Author: roboth
Subject: select one item from months [question about getting one in January]
*/
/*
Csdn Problems
Currently, Tables A and B are available.
Table
Userid Username
1 Zhang San
2 Li Si
Table B
Userid userlevel
1 1
1 2
1 3
2 1
2 2
Now we need to use an SQL query or view to get the userid of Table A with the highest userlevel in Table B and then output userid username and usertoplevel.
Userid username usertoplevel
1 Zhang San 3
2 Li Si 2
*/
My solution
-- Prepare data
Declare @ a table (userid int, username varchar (5 ))
Insert into @
Select 1, 'zhang san'
Union all
Select 2, 'Li si'
Declare @ B Table (userid int, userlevel INT)
Insert into @ B
Select 1, 1
Union all
Select 1, 2
Union all
Select 1, 3
Union all
Select 2, 1
Union all
Select 2, 2
-- Method1
Select
Max (A. username ),
B. userid, max (B. userlevel) as toplevel
From @ B
Inner join @
On a. userid = B. userid
Group by B. userid
-- Method2
Select a. username, B .*
From @ B
Inner join @
On a. userid = B. userid
Where
Not exists (select 1 from @ B B1 where b1.userlevel> B. userlevel and b1.userid = B. userid)
-- Method3
Select a. username, B .*
From @ B
Inner join @
On a. userid = B. userid
Where
1> (select count (1) From @ B B1 where b1.userlevel> B. userlevel and b1.userid = B. userid)
-- Method4
Select a. *, (select max (B. userlevel) from @ B where B. userid = A. userid)
From @
-- Method5
Select a. *, (select top 1 (B. userlevel) from @ B where B. userid = A. userid order by B. userlevel DESC)
From @
-- Method6
select. *, B. userlevel
from @ A
Inner join
(
select userid, max (userlevel) as userlevel
from @ B
group by userid
) B
On. userid = B. userid