Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 使用SQL查询中的多个别名作为Excel中列的标题_Mysql_Sql_Excel_Vba - Fatal编程技术网

Mysql 使用SQL查询中的多个别名作为Excel中列的标题

Mysql 使用SQL查询中的多个别名作为Excel中列的标题,mysql,sql,excel,vba,Mysql,Sql,Excel,Vba,关于,我运行以下查询到 a) 在列a和 b) 将别名作为标题包含在列A的SQL中 Sub ConnectDB5() Dim conn As New ADODB.Connection Dim rs As New ADODB.Recordset Dim dateVar As Date Set conn = New ADODB.Connection conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver};

关于,我运行以下查询到

a) 在
列a

b) 将别名作为
标题
包含在
列A的
SQL

Sub ConnectDB5()
    Dim conn As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Dim dateVar As Date

    Set conn = New ADODB.Connection
    conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost; DATABASE=bi; UID=username; PWD=password; OPTION=3"
    conn.Open

    strSQL = " SELECT 'campaign'  UNION ALL SELECT " & _
            " cID AS Campaign " & _
            " FROM PDW_DIM_Offers_Logistics_history " & _
            " WHERE DATE(insert_timestamp) = ""2020-02-24"" "

    Set rs = New ADODB.Recordset
    rs.Open strSQL, conn, adOpenStatic

    Sheet4.Range("A1").CopyFromRecordset rs

    rs.Close
    conn.Close

End Sub
这个查询非常有效


现在,我在SQL查询中添加了一列:

Sub ConnectDB5()
    Dim conn As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Dim dateVar As Date

    Set conn = New ADODB.Connection
    conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost; DATABASE=bi; UID=username; PWD=password; OPTION=3"
    conn.Open

    strSQL = " SELECT 'campaign'  UNION ALL SELECT " & _
            " cID AS Campaign, " & _
            " SUM(order_quantity) AS Quantity" & _
            " FROM PDW_DIM_Offers_Logistics_history " & _
            " WHERE DATE(insert_timestamp) = ""2020-02-24"" " & _
            " GROUP BY 1"


    Set rs = New ADODB.Recordset
    rs.Open strSQL, conn, adOpenStatic

    Sheet4.Range("A1").CopyFromRecordset rs

    rs.Close
    conn.Close

End Sub
有了这个,我得到了:

运行时错误'-2147217887(80040e21)'

我需要将VBA中的内容更改为什么

a) 获取
列a中的活动和
列B中的数量

b) 将别名作为
列A
列b
标题包含在
SQL
中?

我认为您需要修复标题行:

strSQL = " SELECT 'campaign', 'Quantity'  UNION ALL SELECT " & _

UNION要求所有数据集具有相同的列数。

使用UNION时,所选数据集中的列数必须相同: 试试这个:

strSQL = " SELECT 'campaign', '' AS Quantity  UNION ALL SELECT " & _
        " cID AS Campaign, " & _
        " SUM(order_quantity) AS Quantity" & _
        " FROM PDW_DIM_Offers_Logistics_history " & _
        " WHERE DATE(insert_timestamp) = ""2020-02-24"" " & _
        " GROUP BY 1"

在第一次选择时,“数量”列将没有类似的结果。

当我运行此操作时,不会插入B列。它仅插入带有活动的列A。