即使记录不存在也返回行LEFT join with group by clause

时间:2015-05-18 07:21:57

标签: mysql database

我有两张桌子

table_lead

customer_id  created_on             rating_id
1889         2015-02-26 06:24:54    2
1890         2015-03-02 11:27:16    3
1892         2015-03-03 08:19:30    2
1899         2015-03-09 10:56:24    2
1902         2015-03-10 07:21:40    2
1904         2015-03-20 07:28:05    2
1908         2015-04-01 12:34:47    4
1909         2015-04-06 03:29:26    4
1922         2015-04-27 07:00:36    3
1926         2015-04-29 10:31:06    2
1929         2015-05-01 11:59:08    1
1931         2015-05-05 08:49:38    1
1933         2015-05-05 08:56:17    1
1939         2015-05-05 10:29:45    1
1940         2015-05-05 10:36:20    1

table_ratings

rating_id   rating
1           Cold
2           Warm
3           Hot
4           Lost

我想根据评分表中一年中所有月份的评分来计算所有潜在客户的数量我使用以下查询

SELECT COUNT(t2.rating_id),MONTHNAME(t1.created_on),t2.rating,t1.rating_id FROM customer_detail t1
RIGHT JOIN master_lead_rating t2 ON t1.rating_id = t2.rating_id 
WHERE t1.is_lead = 1 AND YEAR(t1.created_on) =2015 GROUP BY STR_TO_DATE(t1.created_on, '%Y-%m'),t2.rating_id

但此查询的结果是

COUNT(t2.rating_id) MONTHNAME(t1.created_on)    rating  rating_id
1                   February                    Warm    2
4                   March                       Warm    2
1                   March                       Hot     3
1                   April                       Warm    2
1                   April                       Hot     3
1                   April                       Lost    4
5                   May                         Cold    1

我想显示等级的计数null或0如果不存在则会像2月那样出现热/丢失/冷的行,计数为0或null ..我该怎么做?

2 个答案:

答案 0 :(得分:0)

SELECT COUNT(c.rating_id)
     , MONTHNAME(c.created_on)
     , r.rating
     , r.rating_id 
  FROM ratings r
  LEFT 
  JOIN customer_detail c
    ON c.rating_id = r.rating_id 
   AND c.is_lead = 1 
   AND c.created_on BETWEEN '2015-01-01' AND '2015-12-31' 
 GROUP 
    BY DATE_FORMAT(c.created_on, '%Y-%m')
     , r.rating_id;

答案 1 :(得分:0)

添加此表格;

create table `cal` (
    `id` int,
    `cal_name` varchar (60)
); 

insert into `cal` (`id`, `cal_name`) values ('1', 'January'),('2', 'February'),('3', 'March'),('4', 'April'),('5', 'May'),('6', 'June'),('7', 'July'),('8', 'August'),('9', 'September'),('10', 'October'),('11', 'November'),('12', 'December');

然后执行此查询;

select cal.cal_name, count(rating_id), master_lead_rating.rating, master_lead_rating.rating_id
from cal
left join customer_detail on month(customer_detail.created_on) = cal.id
left join master_lead_rating on master_lead_rating.rating_id = customer_detail.rating_id
group by id

99%确定它有效,在完成测试之前,sqlfiddle就死了。