MySQL query – find repeat payers in a table for year and month

  Kiến thức lập trình

I am trying to find the number of members who have renewed their memberships for a given month and year. Members need to renew each year, and I would like to know for each month and year how many members:

  1. In total paid for a membership
  2. How many used a card to pay
  3. How many used a coupon to pay
  4. How many renewed their membership for that month / year (based on if there is already a previous entry for their member_id in the table)

I have these two queries which need to be combined. The first query is working fine. The second query has two placeholder values in square brackets [] that should be replaced with the month and year from the first query.

I have tried creating a temp table and then querying that but I keep getting a value of 0 for repeat payers.

SELECT 
  YEAR(FROM_UNIXTIME(payment_date)) AS year,
  MONTH(FROM_UNIXTIME(payment_date)) AS month, 
  COUNT(*) AS total,
  SUM(CASE WHEN COALESCE(coupon, '') = '' THEN 1 ELSE 0 END) AS card_payments,
  SUM(CASE WHEN COALESCE(coupon, '') != '' THEN 1 ELSE 0 END) AS coupon_payments
FROM fees
WHERE status = 'succeeded'
GROUP BY year, month
ORDER BY year DESC, month DESC;

SELECT COUNT(*)
FROM fees 
WHERE MONTH(FROM_UNIXTIME(payment_date)) = [month] 
AND YEAR(FROM_UNIXTIME(payment_date)) = [year]
AND status = 'succeeded'
GROUP BY member_id
HAVING COUNT(*) > 1;

LEAVE A COMMENT