Solution to a database query Problem

Source: Internet
Author: User

/*
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.