0

我使用的表格示例如下:

    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

谢谢你的帮助。

4

1 回答 1

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

如果您想要的通知结果是 each 的每个不同的总计数process_numberid_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

于 2013-05-29T18:30:10.690 回答