MySQL使用条件计数多个不同的记录

时间:2011-06-30 17:52:56

标签: mysql count distinct

我有一个记录所有用户跨配置文件访问的表,我需要获取自指定的UNIX时间戳(:time)以来不同访问次数和指定配置文件(:user_id)的新访问次数。 / p>

id  | user_id  | visitor_id |  time (unix)
====+==========+============+=============
  1 |     1    |       5    |  1300000000
  2 |     1    |       5    |  1300000010
  3 |     1    |       8    |  1300000015
  4 |     1    |       9    |  1300000020
  5 |     1    |       9    |  1300000025
  6 |     1    |       9    |  1300000030

到目前为止,我只能获得总访问量,但无法获得新访问次数。

SELECT COUNT(DISTINCT v.visitor_id) AS total, SUM(v.time > 1300000012) AS new FROM profile_visits v WHERE v.user_id = 1

返回

total | new
============
   3  |   4

但所需的结果是

total | new
============
   3  |   2

2 个答案:

答案 0 :(得分:4)

您可能想要SUM(v.time > 1300000012) AS new

表达式为0或1. COUNT()将为0计为0,但SUM()将仅“计数”1。


重新评论:

SELECT COUNT(t.visitor_id) AS total, SUM(t.subtotal_new) AS total_new
FROM (SELECT v.visitor_id, SUM(v.time > 1300000012) AS subtotal_new
  FROM profile_visits AS v GROUP BY v.visitor_id) AS t

内部查询的SUM()计算每位访问者的新访问次数。外部查询的SUM()为所有访问者提供的新访问次数

答案 1 :(得分:2)

select * from

((SELECT COUNT(DISTINCT v.visitor_id)  
FROM profile_visits v WHERE v.user_id = 1) AS total,

(SELECT COUNT(DISTINCT v.visitor_id)  
FROM profile_visits v WHERE v.time > 1300000012 and v.user_id = 1) AS new) AS Result