mysql:计算所有组中的重复行

时间:2015-10-26 07:33:52

标签: mysql

我们说我有以下表格:

id  |       fb_id    |   date    | 
----     ----------    ---------     
1         1123           2009-1-1        
2         1145           2009-1-1       
3         1123           2009-1-2        
4         1176           2009-1-2        

我想计算每个日期的总用户数,唯一身份用户总数和返回用户数。

我的代码现在正是这个:

SELECT count(DISTINCT fb_id) as uniqueUsers, count(fb_id) as totalUsers, DATE_FORMAT(date, '%d %b %y') as zoom  FROM ".PREFIX."zoom GROUP BY YEAR(date), MONTH(date), DAY(date)

我期待以下结果:

Group 2009-1-1:
-total users: 2
-unique users: 2
-returning users:0

Group 2009-1-2:
-total users: 2
-unique users: 1
-returning users:1 (total users - unique users)

但相反,我得到了:

Group 2009-1-1:
-total users: 2
-unique users: 2
-returning users:0

Group 2009-1-2:
-total users: 2
-unique users: 2
-returning users:0 (total users - unique users)

我有什么想法可以使这项工作?

2 个答案:

答案 0 :(得分:0)

那是因为你在YEAR(date),MONTH(date)等进行了GROUP BY ... 您应该在“日期”(日期)'仅

SELECT count(DISTINCT fb_id) as uniqueUsers,
count(fb_id) as totalUsers,
 DATE_FORMAT(date, '%d %b %y') as zoom  FROM ".PREFIX."zoom GROUP BY DATE(date)

希望这有帮助

答案 1 :(得分:0)

你可以自我加入。像这样的东西

示例数据

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, 1176, '2009-01-02 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;

SQL Fiddle

<强>输出

totalUsers  returningUsers  uniqueUsers zoom
2   0   2   01 Jan 09
2   1   1   02 Jan 09