【问题标题】:MySQL Count multiple distinct records with conditionMySQL根据条件计算多个不同的记录
【发布时间】:2011-09-26 04:59:20
【问题描述】:

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

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

【问题讨论】:

  • 检查我在下面写的查询

标签: mysql count distinct


【解决方案1】:

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

表达式是 0 或 1。COUNT() 会像 1 一样愉快地计算 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() 给出了所有访问者的总新访问次数

【讨论】:

  • 请允许我纠正自己,我实际上使用的是SUM(v.time > 1300000012),它返回 4(COUNT 返回 6),但我只需要获得不同的访问者,因为 1300000012 有一次来自 visitor_id 8 的访问,并且来自 visitor_id 9 的 3 次访问,但这应该算作 2 个新访问者。
  • 我最终对您的解决方案进行了一些修改:SELECT COUNT(t.visitor_id) AS total, SUM(t.subtotal_new) AS total_new FROM (SELECT v.visitor_id, (MAX(v.time) > 1300000012) AS subtotal_new FROM profile_visits v WHERE v.user_id = 1 GROUP BY v.visitor_id) AS t
  • 好的,我误解了您的要求,但很高兴能帮助您找到正确的解决方案。
【解决方案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

【讨论】:

    猜你喜欢
    • 2021-08-24
    • 1970-01-01
    • 2011-05-12
    • 2022-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多