0

I am trying to get a table in excel via VBA connected to MYSQL data base. My query works but I would like to modify something in the results. Right now, I am getting the number of users that purchased 1, 2, 3..... in each column depending on the time variable j. However, for various values of j, there are no users that purchases 3 times or more. I would like to add a function that would say: if number of purchases equal 3, 4, 5 up to 10 does not exist, add value = 0 to that value.

For example: for j = 10 I get :

nb 1 :31 nb 3 :10

I would like to get

nb 1 :31 nb 2 :0 nb 3 :10 nb 4 :0 ......... nb 10 :0

Here is my code:

   For j = 1 To 30

    strSql = "SELECT COUNT(nb_purchases), nb_purchases from users" & _
     "WHERE DATEDIFF(date_added , register_date) >=" & j & " " & _
     "GROUP BY nb_purchases" & _
     "ORDER BY nb_purchases ASC ; "

    For i = 1 To 2
    Cells(i, j) = res(0, i)
    Next i
    Next j
4

1 回答 1

0

您可能希望case-when-then在 mysql 查询中使用:

strSql = "SELECT COUNT(nb_purchases) as CountUsers,"+
         " (CASE WHEN (CountUsers > 2 & CountUsers <11) "+
                " THEN 0 ELSE CountUsers END) AS COUNTTOUSE, " +
        "nb_purchases from users" & _
        "WHERE DATEDIFF(date_added , register_date) >=" & j & " " & _
        "GROUP BY nb_purchases" & _
        "ORDER BY nb_purchases ASC ;

使用COUNTTOUSEfrom result 在 excel 中写入。

于 2012-11-05T16:50:44.167 回答