将mysql查询结果导出到csv文件的问题

06odsfpq  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(391)

我想将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;
7fhtutme

7fhtutme1#

我认为你没有正确定义行尾字符。在windows中,您可能必须使用:

LINES TERMINATED BY '\r\n'

正确读取文件。好像 VENDOR_NAME 列具有 '\r' 字符串末尾的字符。
有关详细信息,请检查加载数据填充语法

相关问题