Mysql计数组由几个标准组成

时间:2013-05-29 18:22:54

标签: mysql

我使用的表格示例如下:

    id_user  | process_number |    date   
  ---------------------------------------
      01     |        1       | 2012-05-04
      01     |        1       | 2012-05-04
      02     |        0       | 2012-05-04
      01     |        1       | 2012-05-05
      01     |        2       | 2012-05-05
      01     |        0       | 2012-05-05
      02     |        0       | 2012-05-05
      03     |        1       | 2012-05-05
      04     |        2       | 2012-05-05
      05     |        1       | 2012-05-05
      05     |        1       | 2012-05-05
      06     |        0       | 2012-05-05
      07     |        3       | 2012-05-05

我想得到的结果是唯一进程的数量(按id_user分组),总进程数(按日期分组)和process_number不等于“0”时的不同用户数(按日期和按日期分组)用户)。我试图用查询来实现这个目标:

SELECT COUNT( DISTINCT id_user ) AS user_process, COUNT( * ) AS total_process, DATE( date) AS date_process, SUM( IF( process_number = '0', 0, 1 ) ) notification FROM a_proces GROUP BY DATE( date ) ORDER BY DATE( date ) DESC LIMIT 0 , 10

此查询添加给定日期的所有用户,这些用户在通知列中有多个process_number大于零。此示例中的正确结果应如下所示:

 date_process    |       user_process       |        total_process     |  notification
 ------------------------------------------------------------------------------
   2012-05-04    |            2             |              3           |       1
   2012-05-05    |            7             |              10          |       6

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您应该可以使用以下内容:

SELECT DATE_FORMAT( date, '%d/%m/%Y' ) AS date_process,
  COUNT(DISTINCT id_user) AS user_process, 
  COUNT( * ) AS total_process, 
  count(distinct case when process_number <> 0 then id_user end) notification 
FROM a_proces 
GROUP BY DATE( date ) 
ORDER BY DATE( date ) DESC 
LIMIT 0 , 10;

请参阅SQL Fiddle with Demo

如果您想要的通知结果是每个process_number的每个不同id_user的总计数,那么您可以使用:

SELECT DATE_FORMAT( p.date, '%d/%m/%Y' ) AS date_process,
  COUNT(DISTINCT p.id_user) AS user_process, 
  COUNT( * ) AS total_process, 
  d.notification 
FROM a_proces p
INNER JOIN
(
  select count(process_number) notification, date
  from
  (
    select distinct id_user, process_number,
      DATE_FORMAT( date, '%d/%m/%Y' ) date
    from a_proces
    where process_number <> 0
  ) d
  group by date
) d
  on DATE_FORMAT( p.date, '%d/%m/%Y' )  = d.date
GROUP BY DATE( p.date ), d.notification
ORDER BY DATE( p.date ) DESC 
LIMIT 0 , 10;

请参阅SQL Fiddle with Demo