结合两个mysql查询的问题

时间:2014-03-15 17:19:52

标签: mysql ruby-on-rails-3 ruby-on-rails-4

我有两个问题,我希望合并为一个。此查询将由rails应用程序中的主干调用。最终结果应如下所示。提前谢谢。

标题展示次数已完成 测试1234 500 34

SELECT title, count(*) as impressions FROM `stats`
WHERE `stats`.`user_id` = 2 
AND (stats.event ='play' and videopos = '0') 
AND (date_time between '2014-03-08 00:00:00' and '2014-03-15 23:59:59') 
GROUP BY title;

SELECT title, count(*) as completed FROM `stats`
WHERE `stats`.`user_id` = 2 
AND (stats.event ='completed') 
AND (date_time between '2014-03-08 00:00:00' and '2014-03-15 23:59:59') 
GROUP BY title;

4 个答案:

答案 0 :(得分:1)

试试:

  SELECT title,(select count(*)  FROM `stats`  WHERE stats.event ='play' and videopos = '0' AND `stats`.`user_id` = 2 AND (date_time between '2014-03-08 00:00:00' and '2014-03-15 23:59:59') ) as impressions ,(select count(*)  FROM `stats`  WHERE stats.event ='completed' AND `stats`.`user_id` = 2 AND (date_time between '2014-03-08 00:00:00' and '2014-03-15 23:59:59') ) as completed
  FROM `stats`
  WHERE `stats`.`user_id` = 2
  AND (date_time between '2014-03-08 00:00:00' and '2014-03-15 23:59:59') 
  GROUP BY title;

答案 1 :(得分:0)

如果您只想合并结果,请使用UNION/UNION ALL

SELECT title, count(*) as impressions FROM `stats`
WHERE `stats`.`user_id` = 2 
AND (stats.event ='play' and videopos = '0') 
AND (date_time between '2014-03-08 00:00:00' and '2014-03-15 23:59:59') 
GROUP BY title

UNION 

SELECT title, count(*) as completed FROM `stats`
WHERE `stats`.`user_id` = 2 
AND (stats.event ='completed') 
AND (date_time between '2014-03-08 00:00:00' and '2014-03-15 23:59:59') 
GROUP BY title;

答案 2 :(得分:0)

试试这个:

SELECT title, 

Sum(Case When `stats`.`user_id` = 2 
AND (stats.event ='play' and videopos = '0') 
AND (date_time between '2014-03-08 00:00:00' and '2014-03-15 23:59:59' Then 1 Else 0 End) 
 as impressions , 

Sum(Case When `stats`.`user_id` = 2 
AND (stats.event ='completed') 
AND (date_time between '2014-03-08 00:00:00' and '2014-03-15 23:59:59') Then 1 Else 0 End) 
 as completed

FROM `stats`
WHERE (`stats`.`user_id` = 2 
AND (stats.event ='play' and videopos = '0') 
AND (date_time between '2014-03-08 00:00:00' and '2014-03-15 23:59:59') )
OR
(`stats`.`user_id` = 2 
AND (stats.event ='completed') 
AND (date_time between '2014-03-08 00:00:00' and '2014-03-15 23:59:59') )
GROUP BY title;
顺便说一下,我来自ms-sql-server后台,但我在语法时检查了mysql的情况。我输入了记事本,未经测试。但是我希望你能抓住总和案例,当你提出要求时,将其调整为你的要求。

答案 3 :(得分:0)

我明白了。这对我有用。

SELECT s.date as date, s.title as title,
  count(F.id) as impressions,
  count(D.event) as completed
FROM stats s
  Left Join stats as F on s.id = F.id and F.event ='play' and F.videopos = '0'
  Left Join stats as D on s.id = D.id and D.event = 'completed'
WHERE s.user_id = '2'
AND (s.date_time between '2014-03-08 00:00:00' and '2014-03-18 23:59:59')
AND s.title is not null
GROUP BY s.title