mysql:count total,unique,返回用户

时间:2015-11-02 09:11:36

标签: mysql

我有下表:

 04  04  05
  2   2   2
  1   2   1
312 212 421

这是我到目前为止的mysql代码:

CREATE TABLE zoom
    (`id` int, `fb_id` int, `date` datetime);

INSERT INTO zoom
    (`id`, `fb_id`, `date`)
VALUES
    (1, 1123, '2009-01-01 00:00:00'),
    (2, 1145, '2009-01-01 00:00:00'),
    (3, 1123, '2009-01-02 00:00:00'),
    (4, 1198, '2009-01-02 00:00:00'),
    (5, 1176, '2009-01-02 00:00:00'),
    (6, 1176, '2009-01-03 00:00:00'),
    (7, 1123, '2009-01-03 00:00:00'),
    (8, 1177, '2009-01-03 00:00:00'),
    (9, 1200, '2009-01-03 00:00:00');

运行上面的代码后,我得到了这个结果:

SELECT count(Znew.fb_id) as totalUsers,
count(Zold.fb_id) as returningUsers,
count(Znew.fb_id) - count(Zold.fb_id) as uniqueUsers,
DATE_FORMAT(Znew.date, '%d %b %y') as zoom
FROM zoom Znew
LEFT JOIN zoom Zold
ON Zold.date < Znew.date
AND Zold.fb_id = Znew.fb_id
GROUP BY Znew.date;

在上面的结果中只有前两行是正确的,所以基本上我的mysql代码只适用于2组,第三行显然是错误的。

这是我在运行代码后期望的正确结果:

totalUsers  returningUsers  uniqueUsers zoom
    2             0              2      01 Jan 09
    3             1              2      02 Jan 09
    5             3              2      03 Jan 09

有什么想法? sqlfiddle:http://sqlfiddle.com/#!9/c5e2a/1

1 个答案:

答案 0 :(得分:1)

您在这里和那里只缺少一些DISTINCT个关键字。

SELECT count(distinct Znew.fb_id) as totalUsers,
count(distinct Zold.fb_id) as returningUsers,
count(distinct Znew.fb_id) - count(distinct Zold.fb_id) as uniqueUsers,
DATE_FORMAT(Znew.date, '%d %b %y') as zoom
FROM zoom Znew
LEFT JOIN zoom Zold
ON Zold.date < Znew.date
AND Zold.fb_id = Znew.fb_id
GROUP BY Znew.date;