CSV Format ScreenShot在表1中,有三列:COMPANY,AMOUNT和Vendor。 查询后,我们将得到一个包含6列的表格:VENDOR,A,B,C,D,总计。
SELECT 'VENDOR','A','B','C','D','Total'
UNION ALL
SELECT
VENDOR,
SUM(CASE
WHEN COMPANY = 'A' THEN AMOUNT
ELSE ''
END) AS A,
SUM(CASE
WHEN COMPANY = 'B' THEN AMOUNT
ELSE ''
END) AS B,
SUM(CASE
WHEN COMPANY = 'C' THEN AMOUNT
ELSE ''
END) AS C,
SUM(CASE
WHEN COMPANY = 'D' THEN AMOUNT
ELSE ''
END) AS D,
SUM(AMOUNT) AS Grand_Total
INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/result.csv'
FROM
table1
GROUP BY VENDOR_NAME;
问题是:当我尝试将查询结果导出到新的csv文件结果中时,我发现csv文件中的内容确实很乱... 在我的result.csv中:第一行是VENDORABCDTotal,第二行是Mike12340001234。所有字段和数据都在csv文件的第一列中。
答案 0 :(得分:0)
您需要用逗号终止每个字段,并用换行符终止每一行: 请使用以下命令导出数据:
SELECT 'VENDOR','A','B','C','D','Total'
UNION ALL
SELECT
VENDOR,
SUM(CASE
WHEN COMPANY = 'A' THEN AMOUNT
ELSE ''
END) AS A,
SUM(CASE
WHEN COMPANY = 'B' THEN AMOUNT
ELSE ''
END) AS B,
SUM(CASE
WHEN COMPANY = 'C' THEN AMOUNT
ELSE ''
END) AS C,
SUM(CASE
WHEN COMPANY = 'D' THEN AMOUNT
ELSE ''
END) AS D,
SUM(AMOUNT) AS Grand_Total
INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/result.csv'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
FROM
table1
GROUP BY VENDOR_NAME;
检查此!