在同一查询中选择ip of Count和Count of DISTINCT ip

时间:2013-05-02 11:37:21

标签: mysql sql count group-by distinct

我有一个像这样的表结构:

TABLE NAME : counter

id  |        datetime       |  url  | ip
-------------------------------------------
1   |2013-04-12 13:27:09    | url1  | ip01
2   |2013-04-13 10:55:43    | url2  | ip02
3   |2013-04-14 11:14:12    | url1  | ip03
4   |2013-04-15 23:23:55    | url2  | ip04
5   |2013-05-02 08:34:44    | url1  | ip03

使用智能SELECT查询,我想获取3列:

Distinct URL    |    count of ip            |    count of distinct ip
                |    for each distinct url  |    for each distinct url  
-------------------------------------------------------------------
url1            |    3                      |    2    
url2            |    2                      |    2    

我在by the help of this solution in stackoverflow下面提出了我的查询,它给出了我需要的前两列:

SELECT url, COUNT(*) AS total_ip FROM counter GROUP BY url ORDER BY total_ip DESC

但是如何将第3列添加到我的查询中呢?

你能帮帮我吗?

1 个答案:

答案 0 :(得分:6)

正如您自己提到的,您可以使用DISTINCT关键字来获取不同的URL。使用COUNT计算IPCOUNT(DISTINCT ID),以便为每个IP <{1}}获取不同的URL

试试这个:

SELECT DISTINCT URL AS D_URL
      ,COUNT(IP) AS IP
      ,COUNT(DISTINCT IP) AS D_IP
FROM counter
GROUP BY URL

输出:

╔═══════╦════╦══════╗
║ D_URL ║ IP ║ D_IP ║
╠═══════╬════╬══════╣
║ url1  ║  3 ║    2 ║
║ url2  ║  2 ║    2 ║
╚═══════╩════╩══════╝

See this SQLFiddle