简体   繁体   English

您如何使用时间戳列计算每天的不同值?

[英]How do you count the distinct values for each day using a timestamp column?

I'm using mysql and I'm having trouble thinking of a query to count the number of users/visitors for a certain date range. 我正在使用mysql,但在考虑查询以计算特定日期范围内的用户/访问者数量时遇到麻烦。 The way that I'm currently doing it is using php, I select the date range and process the data in a for loop and then just count them there. 我目前正在使用php的方式,我选择日期范围并在for循环中处理数据,然后在那里进行计数。 It's actually pretty easy, but the problem is that this method does not work for bigger data of a few million rows. 这实际上很容易,但是问题是该方法不适用于几百万行的较大数据。 The alternative is to count the distinct values using mysql only and just return a count and not actual data by utilizing the index on the timestamp column. 另一种方法是仅使用mysql对不同的值进行计数,而仅通过利用timestamp列上的索引来返回计数,而不返回实际数据。 Also, converting the column to a datetime is not an option. 同样,将列转换为日期时间也不是一种选择。 Any ideas how I can achieve this? 有什么想法可以实现这一目标吗?

Here's a sample result set of what I need: 这是我需要的示例结果集:

date     | count
5-01-13     14
5-02-13     44
5-03-13     23
5-04-13     13

My problem is that I don't know how to group the timestamp column by day. 我的问题是我不知道如何按天分组时间戳列。

That should do the trick: 这应该够了吧:

SELECT DATE('datetimecolumn'), COUNT(*) 
  FROM Table 
 GROUP BY DATE('datetimecolumn')

You just have to do the same, but instead add a group by clause: 您只需要执行相同的操作,而是添加group by子句:

SELECT myDate, count(distinct myField) as cnt
FROM myTable
WHERE myDate BETWEEN ? and ?
GROUP by myDate;

Where the "?" 哪里的“?” are the dates you use in your original query. 是您在原始查询中使用的日期。

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

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