连接表以获取日期范围的分组计数

时间:2014-02-15 08:37:31

标签: mysql sql

CREATE TABLE IF NOT EXISTS `card_results` (
  `card_result_id` int(11) NOT NULL AUTO_INCREMENT,
  `lead_id` int(11) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`card_result_id`),
  KEY `created` (`created`),
  KEY `lead_id` (`lead_id`)
) ENGINE=InnoDB;


CREATE TABLE IF NOT EXISTS `leads_result` (
  `lead_id` int(11) NOT NULL,
  `lead_date` date DEFAULT NULL,
  `aff_ref` varchar(50) DEFAULT NULL,
  UNIQUE KEY `lead_id` (`lead_id`),
  KEY `aff_id` (`aff_id`),
  KEY `lead_date` (`lead_date`)
) ENGINE=InnoDB;

我需要得到的是如下所示:

表lead_result中所有结果的计数 表card_results中所有唯一lead_id的计数 由aff_id

分组
   aff_id   |   total_leads_result   |   total_card_results
--------------------------------------------------------------
    123     |          12            |            16   
    124     |          18            |            22   
    125     |          22            |            56   
    126     |          65            |            34   
    127     |          56            |            56   

我有以下查询,但显然缺少行 card_results中有记录,但lead_result中没有记录 对于给定的日期

SELECT 
lr.aff_id,
COUNT(*) total_leads_result,
(SELECT COUNT(DISTINCT cr.lead_id) 
 FROM card_results cr2
 LEFT JOIN leads_result lr2 ON cr.lead_id = lr2.lead_id 
 WHERE lr2.aff_id = lr.aff_id
 AND DATE(created) = CURDATE() ) total_card_results
FROM leads_result lr
WHERE lead_date = CURDATE
GROUP BY lr.aff_id

我有点难过。提前感谢您的任何帮助。

0 个答案:

没有答案