开发者

MySQL Distinct (Unique) values over time

I have a question about constructing a MySQL query. I have a table with one column containing values, and another column containing timestamps. What I'd like to do is get the number of distinct (unique) values for a field from a specific epoch up until various points in time so 开发者_StackOverflow社区that I can plot the number of unique values over time. For example, I'd like the query result to look like the following:

Date, COUNT( DISTINCT col1)

2011-02-01, 10

2011-02-02, 16

2011-02-03, 24

etc.

Note that these values are the number of distinct values starting the same point in time. Currently to accomplish this, I'm using a loop in PHP to iterate a single query for each date and it takes forever since I have a large DB. To give a better picture, the inefficient code I'd like to replace looks like the following:

for($i=0;$i<count($dates),$i++){      
    $qry = "SELECT COUNT (DISTINCT `col1`) FROM `db`.`table` WHERE `Date` BETWEEN '".$EPOCH."' AND '".$dates[$i]."';";    
}

Any help would be appreciated.

Thanks


If understood your question, you can use a GROUP statement:

SELECT StampCol, COUNT(DISTINCT DataCol) FROM MyTable GROUP BY StampCol


SELECT DATE_FORMAT(date_column, "%Y-%m-%d") AS date_column, COUNT(visitors) AS visitors FROM table GROUP BY DATE_FORMAT(date_column, "%Y-%m-%d") ORDER BY date_column desc"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜