Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Select X of each variation of a field 1

Swi

Programmer
Feb 4, 2002
1,975
US
Hi,

What is the best way to select X records of a version within a database.

Ex. - SEQ, NAME, ADDR, CSZ, VERSION

I would like to pull X records of each unique version. There could be 2 versions to an infinite amount.

Thanks.
 
You would need to provide some unique value to determine which X. Are you looking for random records? If so, you would need to add a random calculation into your query.
 
Requirement now change so I am actually going to read it from a CSV using ADO.

Ex. of CSV header - SEQ, NAME, ADDR, CSZ, VERSION

Random records would be fine. Just need to work out the query.

Set connCSV = New ADODB.Connection
connCSV.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & CSVDataPath & ";Extended Properties=" & Chr$(34) & "text;HDR=Yes;FMT=CSVDelimited;IMEX=1" & Chr$(34) & ";"
Set rsCSV = New ADODB.Recordset
rsCSV.Open "SELECT ???????? FROM [XXXXXX.csv]", connCSV, adOpenStatic, adLockReadOnly, adCmdText
 
No sample data? No desired output? That's not much to go on. Typically I would create a calculated column that sequentially numbers records within a VERSION and then select all records with the sequence number less than or equal to X.
 
SEQ, NAME, ADDR, CSZ, VERSION
1,John1 Doe,1 Any St.,Anytown US 11111,A
2,John2 Doe,2 Any St.,Anytown US 22222,A
3,John3 Doe,3 Any St.,Anytown US 33333,B
4,John4 Doe,4 Any St.,Anytown US 44444,B
5,John5 Doe,5 Any St.Anytown US 55555,C

In a quick example, I would like to return the following if the user chose to have 1 record of each but they would have the option to choose how many of they would like to pull for each VERSION.
1,John1 Doe,1 Any St.,Anytown US 11111,A
3,John3 Doe,3 Any St.,Anytown US 33333,B
5,John5 Doe,5 Any St.Anytown US 55555,C
 
Select Distinct VERSION FROM MyTable

You will get:
A
B
C

Now, loop thru the outcome from above and build this SQL:

SELECT TOP (1) * FROM MyTable Where VERSION = 'A'
UNION ALL
SELECT TOP (1) * FROM MyTable Where VERSION = 'B'
UNION ALL
SELECT TOP (1) * FROM MyTable Where VERSION = 'C'


Run this multi-select statement and you should get what you want.
 
Thanks. This is very similar to the way I was thinking of trying Andrzejek. I just did not know if there was a more efficient way.
 

Part and Inventory Search

Sponsor

Back
Top