子计数除以总计数

时间:2018-08-23 19:05:43

标签: sql excel excel-vba

该表名为[Sheet1 $]

我们正在处理第一列[F1],其中填充了范围为1至20的随机数。整个列(共1,048,576行)已填充。

我想找到值为19的行的百分比

我可以创建单独的子查询并进行划分:

"Select Count([F1]) From [Sheet1$] Where [F1]=19;"

除以

"Select Count([F1]) from [Sheet1$]

但是我想将两个查询都放入一个查询中。

编辑:

看起来OLEDB禁止使用CASE WHEN语句,但是我们可以使用IIF()statemnts

https://stackoverflow.com/a/1742005/9721351

Option Explicit
Private Declare PtrSafe Function timeGetTime Lib "winmm.dll" () As Long

Sub main()
Dim started As Long
Dim ended As Long
    Dim cn                                  As ADODB.Connection
    Dim abcCount                            As Long
    Dim pbcCount                            As Long
    Dim strFile                             As String
    Dim filePath                            As String
    Dim inputDirectoryToScanForFile         As String

    started = timeGetTime

    filePath = "Z:\Test\Test1.xlsx"

    Set cn = New ADODB.Connection

        cn.Open _
                "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                "Data Source='" & filePath & "';" & _
                "Extended Properties=""Excel 12.0 Macro;HDR=No;IMEX=1;"";"

        Debug.Print findCount(cn)

        cn.Close
        Set cn = Nothing

    ended = timeGetTime
    Debug.Print "Sum found in " & (ended - started) / 1000 & " seconds"
End Sub

Function findCount(ByRef cn As ADODB.Connection) As Long
    On Error GoTo CleanFail:
    Dim strSql As String
    Dim rs As ADODB.Recordset
    Set rs = New ADODB.Recordset
    strSql = "Select Count([F1]) from [Sheet1$] where [F1]=19;"
    rs.Open strSql, cn
    findCount = rs.GetString
    rs.Close
    Set rs = Nothing
    Exit Function
CleanFail:
    Debug.Print "nothing in file"
End Function

1 个答案:

答案 0 :(得分:0)

从[Sheet1 $]中选择SUM(IIF([F1] = 19,1,0))* 100.0 / SUM(IIF([F1] <> Null,1,0))