我有以下查询,我想知道如何设置ODBC连接,以获得这个excel电子表格。
declare @StartDate DATE
declare @EndDate DATE
SELECT Sum(case when status = 6 then 1 else 0 end) as Failed,
Sum(case when status = 9 then 1 else 0 end) as Successful,
UniqueID
Into #tempsheet1
FROM Documents
WHERE ownerID = 467
and status in (6,9)
and CreationTime between @StartDate and @EndDate
Group By UniqueID
Select D.UniqueID, FromName, ToName, CreationTime,
cast(CreationTime as date) as CreationDate, cast(CreationTime as date) as CreationTime,
ErrorCode, ElapsedSendTime, RemoteID
From #tempsheet1 ts1
Inner Join Documents D On
D.UniqueID = ts1.UniqueID
and [Status] = 9
ORDER BY D.CreationTime desc
我还在网上搜索东西,但是如果有人能指出我正确的方向或给我一些很棒的提示。
答案 0 :(得分:0)
在excel中,转到数据选项卡>获取外部数据>来自其他来源>来自Microsoft Query。从那里取决于您要连接的数据库类型,但向导应指导您完成。
设置好连接后,您可以右键单击结果数据集并选择表格>编辑查询,选择命令类型= SQL,然后根据需要编辑查询。
根据您正在做的事情,ADO数据库连接可能会更好,并允许您设置动态日期过滤器等...但这是另一个主题
编辑:下面的ADO方法
添加对Microsoft ActiveX数据对象库的引用
找出你的连接字符串:https://www.connectionstrings.com/
实施类似下面的内容
Sub adoConExample()
Dim startDate As String
Dim endDate As String
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sql As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
startDate = format("Your date range reference".value, "yyyy-mm-dd")
endDate = format("Your date range reference".value, "yyyy-mm-dd")
With con
.ConnectionString = "Your connection string"
.CursorLocation = adUseClient
.Open
End With
sql = "Your sql string"
sql = Replace(sql, "DATE1", startDate)
sql = Replace(sql, "DATE2", endDate)
rs.CursorLocation = adUseClient
rs.Open sql, con, adOpenStatic, adLockReadOnly, adCmdText
"Your paste target range".CopyFromRecordset rs
con.Close
rs = Nothing
con = Nothing
End Sub