使用row_number返回特定的查询行

时间:2014-07-30 07:46:05

标签: sql sql-server

我正在使用SQL Server 2012& MATLAB。我有一个5列的表(1个字符,1个日期时间和3个浮点数)。我有一个简单的查询如下所示,返回该表中包含超过一百万条记录的数据 - 但这会导致MATLAB中出现内存不足错误。

简单查询

 select id_co, date_r, FAM_Score, FAM_A_Score, FAM_Score
 from GSI_Scores
 where id_co <> 'NULL'
 order by id_co, date_rating

所以我打算细分查询,批量选择250,000条记录中的数据。我刚刚遇到了我添加到查询中的ROW_NUMBER函数,请参阅下文。这为我记录了所有记录。但是我在选择250,000到500,000之间的记录时遇到了麻烦。我该怎么做?

更新后的查询

  select id_co, date_r, FAM_Score, FAM_A_Score, FAM_Score, row_number() over (order by id_co) as num_co
 from GSI_Scores
 where id_co <> 'NULL' and num_sedol between 250000 and 500000
 order by id_co, date_rating

3 个答案:

答案 0 :(得分:3)

只需使用子查询或Common Table Expression(CTE)。

;WITH CTE AS
(
  --Your query
)
SELECT * FROM CTE
WHERE num_co BETWEEN 250000 AND 500000

答案 1 :(得分:0)

只是一个示例

 declare @t table  (ID INT)
 insert into @t (id)values (1)
  insert into @t (id)values (2)
   insert into @t (id)values (3)
  insert into @t (id)values (4)

  ;WITH CTE AS
  (
  select *,COUNT(ID)OVER (PARTITION BY ID  ) RN from @t

 )
 Select ID from CTE C WHERE C.ID BETWEEN 2 AND 4 
 ORDER BY RN 

OR

;WITH CTE (select id_co,
                        date_r, 
                        FAM_Score,
                        FAM_A_Score, 
                        FAM_Score, 
                        COUNT(id_co) over (PARTITION BY ID  DESC) as num_co
                from GSI_Scores
                    where id_co <> 'NULL')
            Select C.d_co,
            C.date_r, 
            C.FAM_Score,
            C.FAM_A_Score, 
            C.FAM_Score FROM CTE C
            WHERE C.id_co between 250000 and 500000
            order by C.id_co, C.date_rating

答案 2 :(得分:0)

您可以尝试使用OFFSET x ROWS FETCH NEXT和ROWS ONLY这样的命令:

CREATE TABLE TempTable (
    TempID INT IDENTITY(1,1) NOT NULL,
    SomeDescription VARCHAR(255) NOT NULL,
    PRIMARY KEY(TempID))

INSERT INTO TempTable (SomeDescription) 
VALUES ('Description 1'),
    ('Description 2'),
    ('Description 3'),
    ('Description 4'),
    ('Description 5'),
    ('Description 6'),
    ('Description 7'),
    ('Description 8'),
    ('Description 9'),
    ('Description 10')

SELECT * FROM TempTable ORDER BY TempID OFFSET 3 ROWS FETCH NEXT 2 ROWS ONLY;