?
Solved

Selecting n rows from similar  rows ms sql 2005

Posted on 2007-10-01
4
Medium Priority
?
325 Views
Last Modified: 2010-03-20
I have a table with 2 fields name and dept.

Say 2000 records an 5 departments.

I need to select 5 names of each department. (No matter which)

I f I needed 1 it woul be very simple

select max(name),dept from table group by dept

But I need 5 not only 1

0
Comment
Question by:robrodp
4 Comments
 
LVL 17

Expert Comment

by:Daniel Reynolds
ID: 19992379

Is this what you are looking for?
SELECT DISTINCT NAME, Dept from table
0
 

Author Comment

by:robrodp
ID: 19992407
No, I want 5 names for each department. Do not care which
0
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 19992463
Hello robrodp,

DECLARE @sql VARCHAR(8000)
SELECT @SQL =  COALESCE(@sql+' union all ', '') +'SELECT TOP 5 name, deptID from urTble WHERE deptid = '''+   deptID +''''+char(13)
FROM urTble

EXEC(@sql)



Aneesh R
0
 
LVL 70

Accepted Solution

by:
Scott Pletcher earned 2000 total points
ID: 19992785
SELECT dept, name
FROM (
    SELECT dept, name, ROW_NUMBER() OVER (PARTITION BY dept ORDER BY NEWID()) AS rowNum
    FROM tableName    
) AS derived
WHERE rowNum <= 5
ORDER BY dept, name


NEWID() will give you a random sampling of names; you could of course ORDER BY name to get the first 5 names.
0

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
MSSQL DB-maintenance also needs implementation of multiple activities. However, unprecedented errors can hamper the database management. In that case, deploying Stellar SQL Database Toolkit ensures fast and accurate database and backup repair as wel…
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.
Suggested Courses

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question