我想将mysql查询结果导出到csv文件中,但是发现有东西 CSV文件格式有误。
输入:
COMPANY AMOUNT VENDOR_NAME
C1 70000 A
C2 6000 A
C3 2000 A
C2 39000 B
C3 4000 B
C3 40000 C
输出:
VENDOR_NAME C1 C2 C3 Total
A
70000 6000 2000 78000
B
0 39000 4000 43000
C
0 0 40000 40000
在我的输出中,供应商名称和其他编号不在同一行中...我不知道为什么。也许我的代码中有一些错误。
这是我的代码。
CREATE TABLE test(
COMPANY VARCHAR(50),
AMOUNT DECIMAL(10,2),
VENDOR_NAME VARCHAR(100)
);
LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/try.csv' INTO TABLE test
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(COMPANY,AMOUNT,VENDOR_NAME);
SELECT 'VENDOR_NAME','C1','C2','C3','Grand Total'
UNION ALL
SELECT
VENDOR_NAME,
SUM(CASE
WHEN COMPANY = 'C1' THEN AMOUNT
ELSE 0
END) AS C1,
SUM(CASE
WHEN COMPANY = 'C2' THEN AMOUNT
ELSE 0
END) AS C2,
SUM(CASE
WHEN COMPANY = 'C3' THEN AMOUNT
ELSE 0
END) AS C3,
SUM(AMOUNT) AS Grand_Total
INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/Result.csv'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
FROM
test
GROUP BY VENDOR_NAME;
答案 0 :(得分:0)
我认为您没有正确定义行尾字符。在Windows中,您可能必须使用:
LINES TERMINATED BY '\r\n'
以正确读取文件。似乎VENDOR_NAME
列的字符串末尾有'\r'
个字符。
有关更多信息,请检查LOAD DATA INFILE Syntax