【问题标题】:Use multiple alias from SQL query as header of columns in Excel使用 SQL 查询中的多个别名作为 Excel 中的列标题
【发布时间】:2020-06-18 05:34:44
【问题描述】:

参考this question,我运行以下查询

a) 获取 Column A
中的广告系列 b) 将SQL 中的别名作为header 包含在Column A 中。

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) 获取 Column A 中的活动和 Column B 中的数量
b) 将SQL 中的别名作为header 包含在Column AColumn B 中?

【问题讨论】:

    标签: mysql sql excel vba


    【解决方案1】:

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

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

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

    【讨论】:

    • 当我运行这个时,B 列没有被插入。它仅在广告系列中插入 A 列。
    【解决方案2】:

    当您使用联合时,您的选择中的列数必须相同。

    试试这个:

    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"
    

    在您的第一次选择中,数量列将没有任何结果。

    【讨论】:

      猜你喜欢
      • 2020-06-18
      • 2014-06-08
      • 2021-03-20
      • 2014-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多