![](/img/trans.png)
[英]Is there a way to export huge amount of data (more than a million rows) from SQL Server to csv?
[英]SQL Server - Export huge amount of record into multiple csv files
我正在運行一個查詢,它給了我超過 800 萬條記錄。 我已將結果導出到 .csv 文件中,但該文件太大而無法處理(8GB...)。
我想要做的是將結果 csv 拆分為多個文件,但有一個條件:
有一個列名“Locator”代表一個 ID。 我已經設法對我的記錄進行分組以獲得那種結果:
Locator | Name | LastName
___________________________
ABCDEFH | Foo | Oof
ABCDEFH | Foo2 | Oof2
ABCDEFH | Foo3 | Oof3
TUVWXYZ | Mark | Mark
TUVWXYZ | Mark2| Mark2
... | ... | ...
所以我想要做的基本上是在不拆分分組的情況下拆分記錄......是否可以這樣做?
編輯:這是 NTILE 的查詢:
with locator as
(
select distinct
pnrlctrnum,
NTILE(8) OVER(ORDER BY pnrlctrnum) as Tile_Num
from ttddocseg, ttddoc, ttdhdr
where ttddocseg.tdtrxnum = ttddoc.tdtrxnum and ttdhdr.tdtrxnum = ttddoc.tdtrxnum
)
select ttdhdr.pnrlctrnum, ttddoc.*, ttddocseg.*
from ttddocseg, ttddoc, ttdhdr
inner join locator on locator.pnrlctrnum = ttdhdr.pnrlctrnum
where Tile_num = 7 and ttddocseg.tdtrxnum = ttddoc.tdtrxnum and ttdhdr.tdtrxnum = ttddoc.tdtrxnum
您可以使用 ntile 函數生成組組。 這將確保組保持在一起,然后您可以將您的導出分成您喜歡的任意多個分區。
更改 thr ntile number 以更改您想要的分組數量,然后您可以將其集成到您的導出過程中。
with locator as
(
select ditinct
Locator,
NTILE(4) OVER(ORDER BY Locator) as Tile_Num
from tbl
)
select *
from tbl
inner join locator on locator.Locator = tbl.Locator
where Tile_num = 3
這種方法有一個錯誤。 在 Person.Address 表中的示例 AdventureWorks DB 上重現相同的示例
with ps as
(
SELECT distinct PostalCode, ntile(6) over (order by PostalCode) as part
FROM [Person].[Address]
)
select * from( select PostalCode, count(distinct part) as part_count from ps group by PostalCode ) as tmp where part_count>1
結果是:
郵政編碼 | 部分計數 |
---|---|
3977 | 2 |
78400 | 2 |
92118 | 2 |
97301 | 2 |
GA10 | 2 |
有一些郵政編碼屬於 1 個以上的組。這是因為分離是首先執行的。 ntile 嘗試在不考慮值的情況下將相同大小的組分開,並且通過在 select 中使用 distinct ,您最終會在每個組中得到不同的值,但正如我們所見,某些值可能會重復。
為避免這種情況再次發生,您應該首先獲得不同的郵政編碼,然后將它們分成幾組,最后執行與主表的連接。
with ps as
(
select PostalCode, ntile(6) over (order by PostalCode) as part
from (select distinct PostalCode from Person.Address ) as tmp
)
select * from Person.Address a inner join ps on a.PostalCode= ps.PostalCode
通過這種方式,您可以將郵政編碼組保留在同一分區中。正如您所看到的,分區中沒有最大值等於下一個分區的最小值。
select ps.part, min(a.PostalCode) as minimum, max(a.PostalCode) as maximum from Person.Address a inner join ps
on a.PostalCode= ps.PostalCode group by ps.part
部分 | 最低限度 | 最大值 |
---|---|---|
1 | 01071 | 32960 |
2 | 33000 | 59100 |
3 | 59101 | 84070 |
4 | 84074 | 94066 |
5 | 94070 | EM15 |
6 | G1R | YO15 |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.