我需要在单个查询

时间:2017-09-13 09:41:04

标签: mysql sql

我需要在一个表结构中合并三个查询和显示

SQL查询:

 SELECT MonthName(created) as Month ,year(created) as Year ,user_type,count(user_type) 
   FROM `cii_registered_users` 
  WHERE verification=1 
    AND activation_step=5 
    AND status=1 
    AND user_type='1' 
    AND year(created)='2017'  
    AND created > CURDATE() - INTERVAL 3 MONTH   
  GROUP BY user_type,month(created),year(created)

  SELECT MonthName(created) as Month ,year(created) as Year ,user_type,count(user_type) 
    FROM `cii_registered_users` 
   WHERE verification=1 
     AND activation_step=5 
     AND status=1 
     AND user_type='2' 
     AND year(created)='2017'  
     AND created > CURDATE() - INTERVAL 3 MONTH   
   GROUP BY user_type,month(created),year(created)

SELECT MonthName(created) as Month ,year(created) as Year ,user_type,count(user_type) 
  FROM `cii_registered_users` 
 WHERE verification=1 
   AND activation_step=5 
   AND status=1 
   AND user_type='3' 
   AND year(created)='2017'  
   AND created > CURDATE() - INTERVAL 3 MONTH   
 GROUP BY user_type,month(created),year(created)

然后我需要单独的行显示除三个间隔和总计数之外的所有用户类型和总计数

  Month     Year    count(user_type=2)      count(user_type=1)   full year count
  June      2017     12                      3
  July      2017     1                       17
  August    2017     10                      8
  September 2017     1                       1

除了这四个月,我需要在另一栏中计算总数

1 个答案:

答案 0 :(得分:1)

这似乎是一种旋转式查询的工作

尝试这样的事情:

 SELECT MONTH(created) as Month,
        YEAR(created) as Year,
        SUM(user_type = '1') user_type_1,
        SUM(user_type = '2') user_type_2,
        SUM(user_type = '3') user_type_3
   FROM table
  WHERE whatever
  GROUP BY MONTH(created), YEAR(created)

为什么这样做?因为,在MySQL中,像user_type = '1'这样的表达式如果为真,则数字值为1,如果为假,则为0

为什么这是一个好方法?它不难阅读和验证,也不需要在需要时进行更改。

如果是我的查询,我会use LAST_DAY()而不是YEAR()MONTH(),如下所示。但也许这只是个人偏好。

SELECT LAST_DAY(created) AS month_ending,
          ...
 GROUP BY LAST_DAY(created)