question

AndrewSkaggs-1300 avatar image
0 Votes"
AndrewSkaggs-1300 asked AndrewSkaggs-1300 answered

Select one max record

I have the following data set:

Loc name visits
8 bob 1
8 bob 2
8 Jan 1
8 Kim 1
8 Liz 1
8 Liz 2
8 Sam 1
8 Sam 2
8 Sam 3
8 Sam 4
15 Joe 1
15 Joe 2
15 Steve 1
15 Steve 2
15 Steve 3
15 Jill 1

How do I write a query off this data set that will pull just 1 record back for each group? I would like to see in my result:

Loc name visits
8 Sam 4
15 Steve 3

Please let me know if you can help.

sql-server-transact-sql
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

MelissaMa-msft avatar image
0 Votes"
MelissaMa-msft answered MelissaMa-msft edited

Hi @AndrewSkaggs-1300

Welcome to Microsoft Q&A!

Please refer to below and check whether it is working.

 create table mytable 
 (Loc int,
 name varchar(10),
  visits int)
    
  insert into mytable values
 (8,'bob', 1),
 (8 ,'bob', 2),
 (8 ,'Jan', 1),
 (8 ,'Kim', 1),
 (8 ,'Liz', 1),
 (8 ,'Liz', 2),
 (8 ,'Sam', 1),
 (8 ,'Sam', 2),
 (8 ,'Sam', 3),
 (8 ,'Sam', 4),
 (15 ,'Joe', 1),
 (15 ,'Joe', 2),
 (15 ,'Steve', 1),
 (15 ,'Steve', 2),
 (15 ,'Steve', 3),
 (15 ,'Jill', 1)

 select a.* from mytable a
 inner join (
 select loc,max(visits) max from mytable
 group  by loc) b
 on a.Loc=b.Loc and a.visits=b.max
 order by a.Loc

Output:

 loc name visits
 8 Sam 4
 15 Steve 3

Best regards,
Melissa


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

AndrewSkaggs-1300 avatar image
0 Votes"
AndrewSkaggs-1300 answered

Hi Melissa,

Yes this worked perfectly for me, thank you for your help

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.