在查询中将SELECT语句导出到Excel

时间:2016-04-29 17:46:18

标签: sql excel select export

所以我需要将这个SELECT语句导出到一个excel文件(比如说我的桌面),但是我需要在查询中完成它,所以它每次都会启动一个新文件(覆盖它)脚本是从从头到尾。 SSIS不是一种选择,也不是标准出口。请参阅下面的SELECT语句。

SELECT
    Sub_Company,
    GL_Account,
    CAST(SUM(Debits) AS DECIMAL(18,2)) AS Debits,
    CAST(SUM(Credits) AS DECIMAL(18,2)) AS Credits,
    CAST(SUM([P&L_Impact]) AS DECIMAL(18,2)) AS [P&L_Impact],
    COUNT(*) AS Record_Count
FROM
(
    SELECT *
    FROM [FL_SQL_Training].[dbo].[Combined_GL]
    WHERE
        Company = 'US' AND
        GL_Source = 'Consolidation'
) A
WHERE
    GL_Journal_Header_Description LIKE '%UK%' OR
    GL_Journal_Header_Description LIKE '%CAD%' OR
    GL_Journal_Header_Description LIKE '%MEX%' OR
    GL_Journal_Header_Description LIKE '%Hon%'
GROUP BY
    Sub_Company,
    GL_Account

谢谢,

2 个答案:

答案 0 :(得分:0)

SELECT
    Sub_Company,
    GL_Account,
    CAST(SUM(Debits) AS DECIMAL(18,2)) AS Debits,
    CAST(SUM(Credits) AS DECIMAL(18,2)) AS Credits,
    CAST(SUM([P&L_Impact]) AS DECIMAL(18,2)) AS [P&L_Impact],
    COUNT(*) AS Record_Count
    INTO OUTFILE '/tmp/accounts.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n';
FROM
(
    SELECT *
    FROM [FL_SQL_Training].[dbo].[Combined_GL]
    WHERE
        Company = 'US' AND
        GL_Source = 'Consolidation'
) A
WHERE
    GL_Journal_Header_Description LIKE '%UK%' OR
    GL_Journal_Header_Description LIKE '%CAD%' OR
    GL_Journal_Header_Description LIKE '%MEX%' OR
    GL_Journal_Header_Description LIKE '%Hon%'
GROUP BY
    Sub_Company,
    GL_Account

答案 1 :(得分:0)

创建Excel数据源并插入值

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=D:\testing.xls;', 
'SELECT * FROM [SheetName$]') select * from SQLServerTable

此处提供了更多信息http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926