aggregate queries optimisation I need to aggregate all sales by days to build graph. 

I have such a table 

CREATE TABLE `transaction` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `product_id` varchar(255) NOT NULL,
  `purchase_date` int(10) unsigned NOT NULL DEFAULT '0',
  `expires_date` int(10) unsigned NOT NULL DEFAULT '0',
  `expires_date_calculated` int(10) unsigned NOT NULL DEFAULT '0',
  `payment_account_id` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `payment_account_id` (`payment_account_id`),
  KEY `expires_date` (`expires_date`)
);


with the following data

INSERT INTO transaction
 (product_id, purchase_date, expires_date, expires_date_calculated, payment_account_id) 
VALUES 
 ('a', 1164357246, 0, 1264357246, 2),
 ('a', 1345117819, 0, 1435413246, 1),
 ('b', 1345117907, 0, 1440683646, 2),
 ('c', 1345119400, 1464357246, 0, 5),
 ('b', 1345119625, 0, 1464357246, 10),
 ('a', 1345120085, 0, 1464357246, 2),
 ('b', 1345121092, 0, 1464357246, 5),
 ('a', 1464357246, 0, 1564357246, 2) ;


And I have a function which triggers the following query 32 times with different date values

SELECT COUNT(DISTINCT payment_account_id) AS cnt
FROM transaction
WHERE (purchase_date &lt; 1345120085  
       AND (expires_date &gt; 1345120085 OR expires_date_calculated &gt; 1345120085))
  AND (
    `product_id` IN
    (
      'a',
      'b'
    )
  );


And it works very slow. I want to replace it by one big query with 32 SUM(IF())

SELECT
  sum(IF((purchase_date &lt; 1345120085 
          AND (expires_date &gt; 1345120085 OR expires_date_calculated &gt; 1345120085)), 
        1, 0)) AS day1
#...
FROM (
       SELECT
         payment_account_id,
         (purchase_date)           AS purchase_date,
         (expires_date)            AS expires_date,
         (expires_date_calculated) AS expires_date_calculated
       FROM transaction
       WHERE
         `product_id` IN
         (
           'a',
           'b'
         )
         AND payment_account_id IS NOT NULL
        GROUP BY payment_account_id
     ) AS tmp;


SQL Fiddle with example 

But I get wrong result. What I am doing wrong?
Ok. I found the solution.

SELECT 
  SUM(IF(day1 &gt;0, 1, 0))
  #...
  FROM(
      SELECT
      payment_account_id, sum(day1) AS day1
      #...
        FROM (
           SELECT
             payment_account_id,
             IF((purchase_date &lt; 1345120085 AND (expires_date &gt; 1345120085 OR expires_date_calculated &gt; 1345120085)), 1, 0) AS day1
            #...
           FROM transaction
           WHERE
             `product_id` IN
             (
               'a',
               'b'
             )
             AND payment_account_id IS NOT NULL
          ) AS tmp
      GROUP BY payment_account_id
     )
     AS tmp1;