Link to home
Create AccountLog in
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')
Avatar of Patrick Matthews
Patrick Matthews
Flag of United States of America image

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

Avatar of jb428j
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.
Avatar of 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.
Avatar of jb428j

ASKER

might NOT* be worth the work
ASKER CERTIFIED SOLUTION
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
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.

:)
:) 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

Avatar of jb428j

ASKER

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