使用sql server 2008
我想拿一张有1100万条记录的表格,并将它们分成每块50000块,同时保留原始表格并确保每个块包含唯一记录。 如果我为第一批选择前50000条记录,我怎样才能保证我获得下一条50000等等。
答案 0 :(得分:3)
使用排名函数,特别是row-number():
DECLARE
@From int
,@Thru int
-- Example here would be the second set
SET @From = 50001
SET @Thru = 100000
SELECT <columns>
from (select <columns>, row_number() over (order by <PrimaryKey>) Ranking
from MyTable) xx
where Ranking between @From and @Thru
答案 1 :(得分:3)
尝试NTILE(n),其中n =块数。由于您需要创建“块”表,您应该知道需要多少块,而NTILE会为您正确地分割行:
DECLARE @YourTable table (RowID int, RowValue varchar(5))
INSERT @YourTable VALUES (1,'A')
INSERT @YourTable VALUES (2,'B')
INSERT @YourTable VALUES (3,'C')
INSERT @YourTable VALUES (4,'D')
INSERT @YourTable VALUES (5,'E')
INSERT @YourTable VALUES (6,'F')
INSERT @YourTable VALUES (7,'G')
INSERT @YourTable VALUES (8,'H')
INSERT @YourTable VALUES (9,'I')
INSERT @YourTable VALUES (10,'J')
INSERT @YourTable VALUES (11,'K')
INSERT @YourTable VALUES (12,'L')
DECLARE @YourTable1 table (RowID int, RowValue varchar(5))
DECLARE @YourTable2 table (RowID int, RowValue varchar(5))
DECLARE @YourTable3 table (RowID int, RowValue varchar(5))
DECLARE @YourTable4 table (RowID int, RowValue varchar(5))
DECLARE @YourTable5 table (RowID int, RowValue varchar(5))
INSERT @YourTable1
SELECT
RowID, RowValue
FROM (SELECT
RowID, RowValue
,NTILE(5) OVER(ORDER BY RowID) AS TableID
FROM @YourTable
) dt
WHERE dt.TableID=1
INSERT @YourTable2
SELECT
RowID, RowValue
FROM (SELECT
RowID, RowValue
,NTILE(5) OVER(ORDER BY RowID) AS TableID
FROM @YourTable
) dt
WHERE dt.TableID=2
INSERT @YourTable3
SELECT
RowID, RowValue
FROM (SELECT
RowID, RowValue
,NTILE(5) OVER(ORDER BY RowID) AS TableID
FROM @YourTable
) dt
WHERE dt.TableID=3
INSERT @YourTable4
SELECT
RowID, RowValue
FROM (SELECT
RowID, RowValue
,NTILE(5) OVER(ORDER BY RowID) AS TableID
FROM @YourTable
) dt
WHERE dt.TableID=4
INSERT @YourTable5
SELECT
RowID, RowValue
FROM (SELECT
RowID, RowValue
,NTILE(5) OVER(ORDER BY RowID) AS TableID
FROM @YourTable
) dt
WHERE dt.TableID=5
SELECT * FROM @YourTable1
SELECT * FROM @YourTable2
SELECT * FROM @YourTable3
SELECT * FROM @YourTable4
SELECT * FROM @YourTable5
输出:
RowID RowValue
----------- --------
1 A
2 B
3 C
(3 row(s) affected)
RowID RowValue
----------- --------
4 D
5 E
6 F
(3 row(s) affected)
RowID RowValue
----------- --------
7 G
8 H
(2 row(s) affected)
RowID RowValue
----------- --------
9 I
10 J
(2 row(s) affected)
RowID RowValue
----------- --------
11 K
12 L
(2 row(s) affected)
答案 2 :(得分:1)
我不确定你为什么要这样,但是这里 -
SELECT * FROM
(
SELECT *, ROW_NUMBER() OVER (ORDER BY yourKey) AS Num FROM YourTable
) X WHERE x.Num BETWEEN 0 AND 49999
然后你会以编程方式增加你的0和49,999(希望,如果你要超过1100万条记录),或者手动增加。