简体   繁体   English

MySQL计算具有不同IP地址的用户代理

[英]MySQL count useragents with distinct IP addresses

I built an app that records user events. 我构建了一个记录用户事件的应用。 Each event contains the user's IP address and their useragent (and other data like a timestamp and other stuff that is not relevant here). 每个事件都包含用户的IP地址及其用户代理(以及其他数据,如时间戳和此处不相关的其他内容)。

I would like to use a single query to get (in one row) the total number of events, the number of distinct IP addresses, and the number of iPad users (number of distinct IP/useragent combinations where ugeragent contains "iPad"). 我想使用一个查询来获取(一行)事件的总数,不同的IP地址的数量和iPad用户的数量(其中ugeragent包含“ iPad”的不同IP /用户代理组合的数量)。

Sample table: EVENTS 样本表:活动

id    ip         useragent
=================================
1    "x1"    "blabla iPad blabla"
2    "x2"    "blabla"
3    "x3"    "blabla iPad blabla"
4    "x3"    "blabla iPad blabla"
5    "x3"    "blabla iPad blabla"

Result expected 预期结果

event_count    ip_count    ipad_users
=======================================
    5             3            2

My attempts 我的尝试

The following query returns 4 iPad users because it does not check IP+useragent. 以下查询返回4个 iPad用户,因为它不检查IP + useragent。

SELECT
    COUNT(*) as event_count,
    COUNT(DISTINCT ip) as ip_count,
    COUNT(IF( useragent LIKE '%iPad%', 1, NULL )) as ipad_users
FROM events

This one only returns 1 iPad user because I'm doing it wrong. 这只返回1个 iPad用户,因为我做错了。

SELECT
    COUNT(*) as event_count,
    COUNT(DISTINCT ip) as ip_count,
    COUNT(DISTINCT ip AND IF( useragent LIKE '%iPad%', 1, NULL )) as ipad_users
FROM events

How can I do this? 我怎样才能做到这一点? The closest related question I could find on SO was this one , but I cannot figure it out. 我在SO上可以找到的最接近的相关问题是这个 ,但我无法弄清楚。

SQL Fiddle SQL小提琴

This set of data should return 3 iPad users. 这组数据应返回3个iPad用户。

I think you just want a condition count(distinct) : 我认为您只需要一个条件count(distinct)

SELECT
    COUNT(*) as event_count,
    COUNT(DISTINCT ip) as ip_count,
    COUNT(DISTINCT (case when useragent LIKE '%iPad%' then ip end)) as ipad_users
FROM events;

That is, count the distinct number of ip s when the user agent is an iPad. 即,当用户代理为iPad时,计算ip的不同数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM