Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select number of record based on a count in a subquery

Tags:

sql

sql-server

I need to return the X number of records in a table based on the count of records in a subquery.

For example, if the TOP 80 PERCENT of records in MYTABLE equals 275 records, then I want to select 275 records from another table.

Can this be done with just plain dynamic SQL, and without creating variables etc?

My predecessor wrote something like this:

DECLARE @RecordVariable int

SET @RecordVariable =
(SELECT COUNT(*) * .8 
FROM MYTABLE)

SELECT TOP (@RecordVariable) *
FROM
MYOTHERTABLE
ORDER BY NEWID()
like image 386
Brian Battles Avatar asked Aug 03 '17 13:08

Brian Battles


People also ask

How do I count rows in SQL subquery?

SELECT FUCNTIONIMLOOKINGFOR(SELECT * FROM anothertable) AS count FROM table; So that count is an integer of how many rows the subquery SELECT * FROM anothertable returns.

How do I count the number of rows in a SELECT query?

To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.

Can I use SELECT in count?

SQL SELECT statement can be used along with COUNT(*) function to count and display the data values. The COUNT(*) function represents the count of all rows present in the table (including the NULL and NON-NULL values).


2 Answers

No need for dynamic SQL either, I wouldn't think.

select top (select cast((count(*) * .8)as int) from YourTable) 
* from YourTable
order by NEWID()
like image 170
S3S Avatar answered Nov 14 '22 22:11

S3S


You can nest the query within the TOP ()

SELECT TOP (Select cast(count(*)*.8 as int) From MYTABLE) *
FROM MYOTHERTABLE
ORDER BY NEWID()

EDIT - Speed-Up Random Select

Here is one method to increase the speed using TABLESAMPLE

SELECT TOP (Select cast(count(*)*.8 as int) From MYTABLE) *
FROM MYOTHERTABLE
TABLESAMPLE (10000 ROWS)  -- could be (50 PERCENT)
ORDER BY NEWID()

This will essentially take a random block of 100,000 rows (change as desired), and then return top N order by NewID()

like image 26
John Cappelletti Avatar answered Nov 14 '22 23:11

John Cappelletti