mySQL,多个COUNT INNER JOIN与GROUP BY DATE()

时间:2015-04-29 15:49:42

标签: mysql count group-by inner-join

我有一个安装日志表,我想从这个表中选择

  1. 状态= 1
  2. 的每日安装次数
  3. 状态= 0
  4. 的每日安装次数
  5. PER DAY的安装次数,状态为IN(0,1)
  6. 字段created_utc是我保存安装unix时间戳的地方。

    这是我的表结构

    CREATE TABLE `installs` (
      `created_utc` int(11) DEFAULT NULL,
      `status` tinyint(1) DEFAULT '1' COMMENT '1 - installed, 0 - deleted'
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

    这是我的查询,它无法正常工作(我选择u.id作为执行内部联接的拐杖......我完全迷失了)

    SELECT
        u.id,
        count(pa.created_utc) AS installs_this_day, UNIX_TIMESTAMP(FROM_UNIXTIME(pa.created_utc, '%Y-%m-%d'))*1000 AS time_utc,
        count(pa2.created_utc) AS installs_active_this_day
    FROM 
        users u
    INNER JOIN installs AS pa ON pa.status = 0
    INNER JOIN installs AS pa2 ON pa2.status = 1
    WHERE u.id = 1
    GROUP BY DATE(from_unixtime(pa.created_utc)), DATE(from_unixtime(pa2.created_utc))
    

    这会导致重复和错误计数。

    1   45  1430280000000   45
    1   36  1430280000000   36
    1   117 1430280000000   117
    1   72  1430280000000   72
    1   36  1430280000000   36
    1   531 1430280000000   531
    1   144 1430280000000   144
    1   36  1430280000000   36
    1   18  1430280000000   18
    1   27  1430280000000   27
    1   9   1430280000000   9
    

    安装表数据的示例

    INSERT INTO `installs` (`created_utc`, `status`)
    VALUES
        (1430320706, 0),
        (1430319316, 0),
        (1430311682, 0),
        (1430311506, 0),
        (1430311498, 0),
        (1430311498, 0),
        (1430311386, 0),
        (1430311370, 0),
        (1430311356, 0),
        (1430311272, 1),
        (1430278530, 1),
        (1430229788, 1);
    

1 个答案:

答案 0 :(得分:0)

我认为你只想要条件聚合,而不是两个或三个连接。像这样:

SELECT UNIX_TIMESTAMP(FROM_UNIXTIME(pa.created_utc, '%Y-%m-%d'))*1000 AS time_utc,
       sum(pa.status in (0, 1)) as total_installs,
       sum(pa.status = 0) as installs_status0,
       sum(pa.status = 1) as installs_status1
FROM installs pa
GROUP BY UNIX_TIMESTAMP(FROM_UNIXTIME(pa.created_utc, '%Y-%m-%d'))*1000;