简体   繁体   中英

Calculating simple statistics on a single mysql table

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM