一起加入查询

时间:2014-03-19 18:49:12

标签: mysql

我有两个查询,我与UNION ALL一起为移动潜在客户进行计数,另一个用于网络潜在客户。但不完全确定如何将两个结果合二为一。这是我的疑问:

  SELECT CAST( submitdate AS DATE ) as submitdate, COUNT( DISTINCT name, email, phone, `make` , `model` , `mdlyr` , `miles` ) AS webcount FROM leads WHERE email <> '' and mobile = '0' GROUP BY CAST( submitdate AS DATE )

  UNION ALL

  SELECT CAST( submitdate AS DATE ) as submitdate, COUNT( DISTINCT name, email, phone, `make` , `model` , `mdlyr` , `miles` ) AS mobilecount FROM leads WHERE email <> '' and mobile = '1' GROUP BY CAST( submitdate AS DATE )

但我的结果是两列,表示submitdate,webcount和日期是重复的,并且旁边的计数如下:

  submitdate | webcount
  2014-03-19 | 30
  2014-03-19 | 15
  2014-03-18 | 59
  2014-03-18 | 37

当我试图让它看起来像这样:

  submitdate | webcount | mobilecount
  2014-03-19 | 30       | 15
  2014-03-18 | 59       | 37

我做错了什么?

2 个答案:

答案 0 :(得分:1)

这是一种支点方法。使用你的联盟,但作为“PreQuery”。我添加了一个额外的列,以便通过角色将原点标识为Web或移动。从那以后,我在外层使用它并按日期进行分组,但是无论是什么计数的总和,只是基于网络或移动标志值。

select
      PQ.submitdate,
      sum( case when PQ.leadOrigin = 'W' then PQ.DateCnt else 0 end ) as WebCount,
      sum( case when PQ.leadOrigin = 'M' then PQ.DateCnt else 0 end ) as MobileCount
   from
      ( SELECT 
              CAST( submitdate AS DATE ) as submitdate, 
              MAX( 'W' ) as leadOrigin,
              COUNT( DISTINCT name, email, phone, `make` , `model` , `mdlyr` , `miles` ) AS DateCnt
           FROM 
              leads 
           WHERE 
                  email <> '' 
              and mobile = '0' 
           GROUP BY 
              CAST( submitdate AS DATE )
        UNION ALL
        SELECT 
              CAST( submitdate AS DATE ) as submitdate, 
              MAX( 'M' ) as leadOrigin,
              COUNT( DISTINCT name, email, phone, `make` , `model` , `mdlyr` , `miles` ) AS DateCnt 
           FROM 
              leads 
          WHERE email <> '' 
           and mobile = '1' 
          GROUP BY CAST( submitdate AS DATE ) ) PQ
group by
   PQ.submitdate

答案 1 :(得分:0)

我能够进行此查询:

    SELECT a.submitdate, b.webcount, c.mobilecount
        FROM (
            SELECT DISTINCT CAST( submitdate AS DATE ) AS submitdate FROM leads) AS a
            INNER JOIN 
            (SELECT CAST( submitdate AS DATE ) AS submitdate, COUNT( DISTINCT name, email, phone,  `make` ,  `model` ,  `mdlyr` ,  `miles` ) AS webcount FROM leads WHERE email <> '' AND mobile =  '0' GROUP BY CAST( submitdate AS DATE )) AS b ON a.submitdate = b.submitdate
            INNER JOIN 
            (SELECT CAST( submitdate AS DATE ) AS submitdate, COUNT( DISTINCT name, email, phone,  `make` ,  `model` ,  `mdlyr` ,  `miles` ) AS mobilecount FROM leads WHERE email <>  '' AND mobile =  '1' GROUP BY CAST( submitdate AS DATE )) AS c ON b.submitdate = c.submitdate
    ORDER BY a.submitdate DESC

但是它只给出了2014年3月16日的日期,也就是当Mobile的计数高于0时。有什么东西可以添加到包括所有日期,如果没有则默认为0?