如何改进多个查询

How to improve multiple queries

Objective: 我想为我的简单投币系统计算总分。

代码:长切

MYSQL = "SELECT DISTINCT member_id"
MYSQL = MYSQL & " FROM GameActivityReport"
MYSQL = MYSQL & " WHERE CoinDeposit > 0"

Set rs = New ADODB.Recordset
Debug.Print MYSQL
rs.Open MYSQL, db, adOpenStatic, adLockReadOnly
    
With MainWindow
    If rs.EOF Then
    Else
        .lblCheckerKPITotPWD.Caption = rs.RecordCount
    End If
End With

rs.Close
Set rs = Nothing

MYSQL = "SELECT DISTINCT member_id"
MYSQL = MYSQL & " FROM GameActivityReport"
MYSQL = MYSQL & " WHERE CoinWithdarawal > 0"

Set rs = New ADODB.Recordset
Debug.Print MYSQL
rs.Open MYSQL, db, adOpenStatic, adLockReadOnly
    
With MainWindow
    If rs.EOF Then
    Else
        .lblCheckerKPITotPWW.Caption = rs.RecordCount
    End If
End With

rs.Close
Set rs = Nothing

MYSQL = "SELECT COUNT(*) AS NewCoinDropCount"
MYSQL = MYSQL & " FROM GameActivityReport"
MYSQL = MYSQL & " WHERE CoinDrop > 0"

Set rs = New ADODB.Recordset
Debug.Print MYSQL
rs.Open MYSQL, db, adOpenStatic, adLockReadOnly
    
With MainWindow
    If rs.EOF Then
    Else
        .lblCheckerKPITotPWB.Caption = rs.Fields("NewCoinDropCount")
    End If
End With

rs.Close
Set rs = Nothing

MYSQL = "SELECT DISTINCT member_id"
MYSQL = MYSQL & " FROM GameActivityReport"
MYSQL = MYSQL & " WHERE CoindBalance > 0"

Set rs = New ADODB.Recordset
Debug.Print MYSQL
rs.Open MYSQL, db, adOpenStatic, adLockReadOnly
    
With MainWindow
    If rs.EOF Then
    Else
        .lblCheckerKPITotEC.Caption = rs.RecordCount
    End If
End With

rs.Close
Set rs = Nothing

db.Close
Set db = Nothing

问题:如何让上面的代码变短

按照 Ozgun 的建议,创建联合查询

Option Explicit
Sub counts()

    Dim conn As ADODB.Connection, rs As ADODB.Recordset
    Dim sql(3) As String, sql_all As String, counts(4) As Integer

    sql(0) = " SELECT 1,COUNT(DISTINCT member_id) FROM GameActivityReport " & _
             " WHERE CoinDeposit > 0"
    sql(1) = " SELECT 2,COUNT(DISTINCT member_id) FROM GameActivityReport " & _
             " WHERE CoinWithdrawal > 0"
    sql(2) = " SELECT 3,COUNT(*) FROM GameActivityReport " & _
             " WHERE CoinDrop > 0"
    sql(3) = " SELECT 4,COUNT(DISTINCT member_id) FROM GameActivityReport " & _
             " WHERE CoinBalance > 0"
  
    sql_all = Join(sql, vbCrLf & " UNION " & vbCrLf)

    ' get connection, run sql
    Set conn = ??? ' establish a connection 
    Set rs = conn.Execute(sql_all)
    Do While Not rs.EOF
        counts(rs(0)) = rs(1)
        rs.MoveNext
    Loop

    With MainWindow
        .lblCheckerKPITotPWD.Caption = counts(1)
        .lblCheckerKPITotPWW.Caption = counst(2)
        .lblCheckerKPITotPWB.Caption = counts(3)
        .lblCheckerKPITotEC.Caption = counts(4)
    End With
    conn.Close

End Sub