user219628
user219628

Reputation: 3905

T-SQL select sample records of distinct values

In SQL server 2008 I have table Theory with columns Thesis and Class.

Thesis                   Class
<this is sample text>    1
<this is sample text>    2
<this is sample text>    2
<this is sample text>    3
<this is sample text>    3
<this is sample text>    1
<this is sample text>    3
<this is sample text>    1
<this is sample text>    1
<this is sample text>    2

I want to write select statement that will return two records of each class.

Many thanks

Upvotes: 0

Views: 478

Answers (1)

Martin Smith
Martin Smith

Reputation: 453453

;WITH T AS
(
SELECT Thesis, 
       Class, 
       ROW_NUMBER() OVER (PARTITION BY Class ORDER BY (SELECT 0) ) rn
FROM Theory 
)
SELECT Thesis, Class
FROM T 
WHERE rn <=2

Upvotes: 3

Related Questions