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。