Amin Karimi
Amin Karimi

Reputation: 407

How to select a partial of a table for exporting using SQL?

I have a dataset which has about 25 millions rows. I want to export it to ACCESS. However, I cannot export it as a whole. So I exported the top 10 millions rows. I have used the codes which is shown below.

SELECT TOP (10000000) [TRD_EVENT_DT]
  ,[TRD_EVENT_TM]
  ,[TRD_STCK_CD]
  ,[TRD_PR]
  ,[TRD_TUROVR]
FROM [trade92].[dbo].[trade]

Now, I want to select second 10 millions rows and Then final 5 millions rows for export them to ACCESS.

How can I do that?

Upvotes: 1

Views: 1889

Answers (2)

Red Devil
Red Devil

Reputation: 2393

You can also use offset and fetch in your query:

SELECT [TRD_EVENT_DT]
,[TRD_EVENT_TM]
,[TRD_STCK_CD]
,[TRD_PR]
,[TRD_TUROVR]
FROM [trade92].[dbo].[trade]
ORDER BY [TRD_EVENT_DT] 
OFFSET 10000000 ROWS
FETCH NEXT 5000000 ROWS ONLY

Upvotes: 0

Jacob H
Jacob H

Reputation: 2505

You can use a CTE:

;WITH YourQuery AS (

    SELECT ROW_NUMBER() OVER (ORDER BY TRD_EVENT_TM DESC) as RowNumber, *
    FROM trade

    )
SELECT * FROM YourQuery 
WHERE RowNumber BETWEEN 10000001 AND 20000000

Assuming you are using SQL Server, and not one of the other currently tagged RDBMS. To get the final set of rows, change the WHERE clause to:

WHERE RowNumber > 20000000

Upvotes: 2

Related Questions