I want to export mysql query result into csv file but I found there is something wrong with the format of csv file.
Input:
COMPANY AMOUNT VENDOR_NAME
C1 70000 A
C2 6000 A
C3 2000 A
C2 39000 B
C3 4000 B
C3 40000 C
Output:
VENDOR_NAME C1 C2 C3 Total
A
70000 6000 2000 78000
B
0 39000 4000 43000
C
0 0 40000 40000
In my output, the vendor name and other numbers are not in the same row... I don't know why. Maybe there are some mistakes in my code.
Here is my code.
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;
I think you are not correctly defining the end of line characters. In Windows you may have to use:
LINES TERMINATED BY '\r\n'
to read the file properly. It's seems like the VENDOR_NAME
column has the the '\\r'
characters at the end of the string.
For more information check LOAD DATA INFILE Syntax
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.