MYSQL多列COUNT DISTINCT

时间:2015-07-09 03:34:10

标签: mysql sql

我会跟踪谁登录到我们的本地服务器,如下面的数据库所示。

我的数据库结构是:

user     logon          reconnect

mike     2015-07-09
mike                    2015-07-09
mike                    2015-07-09
mike     2015-07-09
john     2015-07-09
john     2015-07-09
john     2015-07-09
pete                    2015-07-09
pete                    2015-07-09
pete                    2015-07-09
matt     2015-07-09
sara     2015-07-09

我正在尝试构建一个查询,以获取一天内有多少DISTINCT用户登录或重新连接,数据应如下所示:

date          totalcount
2015-07-09    4

基本上它在2015-07-09计算了4个用户。

这是我的查询,显示过去14天logons,但不包括reconnects

SELECT DATE(logon) AS `date`, COUNT(DISTINCT `user`) AS totalcount
FROM user_logons
GROUP BY DATE(logon)
ORDER BY DATE(logon) DESC
LIMIT 14

节目:

date         totalcount
2015-07-09   399
2015-07-08   513
2015-07-07   524
2015-07-06   456
2015-07-05   213
2015-07-04   300
2015-07-03   484
2015-07-02   525
2015-07-01   539
2015-06-30   536
2015-06-29   481
2015-06-28   289
2015-06-27   423
2015-06-26   509

我希望将两个列合并,合并它们,然后按日期分组。我在编写查询时遇到问题。请帮忙。

3 个答案:

答案 0 :(得分:3)

使用COALESCE()功能“合并”这两个日期:

SELECT DATE(COALESCE(logon, reconnect)) AS `date`, COUNT(DISTINCT `user`) AS totalcount
FROM user_logons
GROUP BY DATE(COALESCE(logon, reconnect))
ORDER BY DATE(COALESCE(logon, reconnect)) DESC
LIMIT 14

答案 1 :(得分:1)

我的方法是创建两个临时表。第一个包含所有登录事件的userdate列。第二个包含所有重新连接事件的userdate列。将UNION这两个表放在一起后,您可以按date进行分组,然后获取每个日期的不同用户数。

SELECT t.date AS `date`, COUNT(DISTINCT t.user) AS totalcount
FROM
(
    SELECT `user`, DATE(logon) AS `date`
    FROM user_logons
    WHERE DATE(reconnect) ISNULL
    UNION ALL
    SELECT `user`, DATE(reconnect) AS `date`
    FROM user_logons
    WHERE DATE(logon) ISNULL
) t
GROUP BY t.date
ORDER BY t.date DESC

让我补充一点,如果您的值不是NULL,则此方法会更具吸引力,在这种情况下,您无法优雅地使用COALESCE()

答案 2 :(得分:1)

SELECT t.date AS `date`, COUNT(DISTINCT t.user) AS totalcount
FROM
(
    SELECT user, COALESCE(logon,reconnect) AS `date`
    FROM user_logons
) t
GROUP BY t.date
ORDER BY t.date DESC

我试图将Tim Biegeleisen的解决方案与PM 77-1的解决方案结合起来。

试着帮忙。