Avatar of jb428j
jb428j
 asked on

Set a row limit for each value in a WHERE clause

I have multiple values in a WHERE clause and I would like to know how to limit the number of rows for each value.

About 20 rows would be great.

Current Statement:

SELECT *
FROM Table1
WHERE Col1 IN ('Value1','Value2',...'Value14')
Microsoft SQL Server 2008

Avatar of undefined
Last Comment
jb428j

8/22/2022 - Mon
Patrick Matthews

Try UNION:



SELECT TOP 20 *
FROM Table
WHERE Col1 = 'Value1'
UNION ALL
SELECT TOP 20 *
FROM Table
WHERE Col1 = 'Value2'
UNION ALL
SELECT TOP 20 *
FROM Table
WHERE Col1 = 'Value3'
UNION ALL
... you get the idea...
UNION ALL
SELECT TOP 20 *
FROM Table
WHERE Col1 = 'Value14'

Open in new window

jb428j

ASKER
Thank you for the comment. I forgot to add the fact that I didn't want to do multiple UNION ALL statements. I was looking more inline with using ROW_NUMBER, but I am not an advanced SQL Guru.
jb428j

ASKER
I am working with another DBA here and it is looking to be a big pain in the rear and might now be worth the work. However, if someone does figure it out that would be awesome.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
jb428j

ASKER
might NOT* be worth the work
ASKER CERTIFIED SOLUTION
Kevin Cross

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Patrick Matthews

The good news is that I finally broke down and learned how to use ROW_NUMBER (although I still like to kick it old school, to ensure backward compatibility to SQL 2000).

The bad news is that mwvisa1 posted essentially the same code I came up with about 3 minutes before I returned.

:)
Kevin Cross

:) For my buddy, Patrick, here is how you could simulate ROW_NUMBER(), but maintain compatibility with SQL 2000 (explained in Article above).

SELECT {column list}
FROM (
SELECT *
     , COALESCE((
          SELECT COUNT(1) 
          FROM Table1 b 
          WHERE b.Col1 = a.Col1 
          AND b.SomeColumn < a.SomeColumn
       ), 0)+1 RN
FROM Table1 a
WHERE Col1 IN ('Value1','Value2',...'Value14')
) derived
WHERE RN <= 20

Open in new window

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
jb428j

ASKER
You guys are awesome. I appreciate your time and help on this! Fortunately, for me, I work with only SQL 2008. :)