views:

264

answers:

1

I'd like to calculate some simple statistics (percentages) from a table in mysql. The table in question has the following pseudo-schema:

TABLE: coupons
couponId (int)
couponType (int)
customerId (int)
sentOn (datetime)
visitedOn (datetime)
purchasedOn (datetime)

This table tracks unique coupons sent to customers, when they were sent, whether the customer visited the site because of that coupon, and when they purchased the product from that coupon. In many cases, these datetime columns are null, implying the customer did not visit or purchase.

I'd like to calculate visit % by couponType and purchase % by couponType. I'd also like to be able to calculate these for customerId to see which customers have the highest visit % and purchase %.

Since visit % = # visits / # sends, I can calculate the numerator and denominator easily using sql, but I was hoping to calculate the statistics in a single query for couponType and another single query for customerId. Thanks!

A: 

I'd suggest something like this:

SELECT SUM(IF(visitedOn IS NULL, 0, 1)) / COUNT(1) AS percent_visited,
  SUM(IF(purchasedOn IS NULL, 0, 1)) / COUNT(1) AS percent_purchased
FROM coupons
GROUP BY couponType

I assume here that sentOn is never NULL. If that too might sometimes be NULL, just replace the COUNT(1) with SUM(IF(sentOn IS NULL, 0, 1)) too.

VoteyDisciple