简体   繁体   中英

How to export multiple query results to csv using SQL Server?

I have the following queries set up:

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

How do I export the results of all three of these queries at once so that the final spreadsheet looks something like the following:

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

You could incorporate all 3 queries into a single query:

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;

This would place each of the three counts as separate columns. If you really require your exact output, you could try pivoting the above. One way to do this would be to union together your three queries:

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

The Solution is:

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'

Then use the BCP command to export the data to a CSV file: https://docs.microsoft.com/en-us/sql/tools/bcp-utility

You can combine the three queries into one by using the GROUP BY clause on the ZipFile column like so:

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

This will provide exactly the output you requested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM