如何在以下方案中计算每hit_type
个唯一(click
= campaign
)的数量? :
CREATE TABLE statistics
(`id` int, `uid` int, `hit_type` varchar(10), `name` varchar(55), `date` date)
;
INSERT INTO statistics
(`id`, `uid`, `hit_type`, `name`, `date`)
VALUES
(1,'100','visit','campaign1','2015-03-18'),
(2,'100','visit','campaign1','2015-03-19'),
(3,'100','click','campaign1','2015-03-18'),
(4,'100','click','campaign1','2015-03-18'),
(5,'100','click','campaign1','2015-03-20'),
(6,'100','client','campaign1','2015-03-19'),
(7,'100','client','campaign1','2015-03-20'),
(8,'200','visit','campaign1','2015-03-19'),
(9,'200','visit','campaign1','2015-03-19'),
(10,'200','visit','campaign2','2015-03-20'),
(11,'200','click','campaign1','2015-03-18'),
(12,'200','click','campaign1','2015-03-19'),
(13,'200','client','campaign1','2015-03-19'),
(14,'200','client','campaign2','2015-03-20')
;
SELECT `name`,
SUM(IF(`hit_type` = 'click',1,0)) as click ,
SUM(IF(`hit_type` = 'visit',1,0)) as visit,
SUM(IF(`hit_type` = 'client',1,0)) as client
FROM `statistics`
WHERE `name` IN('campaign1','campaign2')
GROUP BY `name`
ORDER BY `name`
答案 0 :(得分:1)
如果您正在寻找独特的日期,那么您可以:
SELECT `name`,
COUNT(DISTINCT CASE WHEN `hit_type` = 'click' THEN date END) as click ,
COUNT(DISTINCT CASE WHEN `hit_type` = 'visit' THEN date END) as visit,
COUNT(DISTINCT CASE WHEN `hit_type` = 'client' THEN date END) as client
FROM `statistics`
WHERE `name` IN('campaign1','campaign2')
GROUP BY `name`
ORDER BY `name`;