VBA SQL聚合备注字段

时间:2018-12-19 09:37:36

标签: sql excel vba aggregation adodb

我从Excel文件中查询来检索键和说明(备注字段)。

来源:

key  | description
k1     long variable text (memo) maybe up to 1000 char
k2     long variable text (memo) maybe up to 1000 char
k3     long variable text (memo) maybe up to 1000 char
k1     shorter than k1 text (memo) maybe up to 1000 char
k2             
k1     could be also empty

结果:

KEY    DESCRIPTION
k1     long variable text (memo) maybe up to 1000 char
k2     long variable text (memo) maybe up to 1000 char
k3     long variable text (memo) maybe up to 1000 char

我的代码是

SELECT 
    key as KEY, 
    IIF(Count(description) = 1, MAX(description), COUNT(description)) AS DESCRIPTION 
FROM Source 
GROUP BY key

但是Excel返回一个错误,它无法聚合备注字段。

有一些优雅的解决方案吗?

我在Provider = Microsoft.ACE.OLEDB.12.0中使用ADOdb

Sub getRs(strSQL As String)
Dim strConn As String
Dim i As Integer

strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "Data Source=" & ThisWorkbook.FullName & ";" & _
        "Extended Properties=Excel 12.0;"

Set Rs = CreateObject("ADODB.Recordset")
Rs.Open strSQL, strConn

End Sub

连接到其他工作簿看起来像(我认为这不是问题)

    "SELECT --Look above-- FROM [Sheet1$] " & _
    "IN '" & ThisWorkbook.Path & "\Src2.xlsb' " & _
    "[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;']"

现在,我尝试通过LEN和IIF函数“剪切”描述:

  SELECT 
    [key] as [KEY], 
    IIF(Count([description]) = 1, 
         IIF(LEN([description])>255, 
            '[CUT]' & MAX(LEFT([description],240)), 
            COUNT([description])), 
         IIF(LEN([description])>255, 
            '[[CUT]' & MAX(LEFT([description],240)) & ']', 
            '[' & COUNT([description]) & ']' )) AS [DESCRIPTION]
   FROM Source 
   GROUP BY [key]

but now I have this error message

0 个答案:

没有答案