如何使用SQL Server将多个查询结果导出到csv?

时间:2017-10-26 17:27:36

标签: sql sql-server tsql

我设置了以下查询:

SELECT COUNT(*) FROM SqlServer_tbl WHERE ZipFile = 'z1'
SELECT COUNT(*) FROM SqlServer_tbl WHERE ZipFile = 'z2'
SELECT COUNT(*) FROM SqlServer_tbl WHERE ZipFile = 'z3'

如何一次导出所有这三个查询的结果,以便最终的电子表格如下所示:

Zipfile  Count
--------------
z1        1200
z2        1350
z3       25500

3 个答案:

答案 0 :(得分:0)

您可以将所有3个查询合并到一个查询中:

SELECT
    SUM(CASE WHEN ZipFile = 'z1' THEN 1 ELSE 0 END) AS zip1_cnt,
    SUM(CASE WHEN ZipFile = 'z2' THEN 1 ELSE 0 END) AS zip2_cnt,
    SUM(CASE WHEN ZipFile = 'z3' THEN 1 ELSE 0 END) AS zip3_cnt
FROM SqlServer_tbl;

这会将三个计数中的每一个作为单独的列。如果您确实需要确切的输出,可以尝试旋转上面的内容。一种方法是将三个查询结合在一起:

SELECT
    'z1' AS Zipfile,
    (SELECT COUNT(*) FROM SqlServer_tbl WHERE ZipFile = 'z1') AS [Count]
FROM SqlServer_tbl
UNION ALL
SELECT 'z2', (SELECT COUNT(*) FROM SqlServer_tbl WHERE ZipFile = 'z2')
FROM SqlServer_tbl
UNION ALL
SELECT 'z3', (SELECT COUNT(*) FROM SqlServer_tbl WHERE ZipFile = 'z3')
FROM SqlServer_tbl

答案 1 :(得分:0)

解决方案是:

SELECT COUNT(*) FROM SqlServer_tbl WHERE ZipFile = 'z1'
Union
SELECT COUNT(*) FROM SqlServer_tbl WHERE ZipFile = 'z2'
Union
SELECT COUNT(*) FROM SqlServer_tbl WHERE ZipFile = 'z3'

然后使用BCP命令将数据导出到CSV文件: https://docs.microsoft.com/en-us/sql/tools/bcp-utility

答案 2 :(得分:0)

您可以使用ZipFile列上的GROUP BY子句将这三个查询合并为一个,如下所示:

SELECT ZipFile, COUNT(*) AS [Count]
FROM SqlServer_tbl 
WHERE ZipFile IN ('z1','z2','z3')
GROUP BY ZipFile
ORDER BY ZipFile

这将准确提供您请求的输出。