0

I have a table like below:

uid nid     points  date                        reason
36  116     2       2012-08-28 11:52:12         session
31  110     2       2012-08-23 15:47:47         session
36  115     2       2012-08-27 11:52:48         session

as u can see uid is not unique, it can be repeated. What i need is to select sum of points for every id between date(30 days before). For example: sum of uid36 = to 4. What i have tried:

$start_time = mktime(0, 0, 0, $today["mon"], ($today["mday"] - 30), $today["year"]);//30 days before
$end_time = time();
$query = db_query("SELECT uid,sum(points), date FROM users_history WHERE date BETWEEN '$start_time' AND '$end_time'");

but how to select for every id

3 Answers 3

4

You need GROUP BY uid, and date is meanless in your query if you are using aggregate function SUM.

SELECT uid, SUM(points) 
FROM users_history 
WHERE date BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 day) AND NOW() 
GROUP BY uid

And if there is no future date, then you only need

WHERE date >= DATE_SUB(CURDATE(), INTERVAL 30 day)
Sign up to request clarification or add additional context in comments.

1 Comment

Also beware that $start_time and $end_time will either need to be passed through FROM_UNIXTIME() or else formatted as suitable literals for MySQL (e.g. using date()).
1

for that you need to group your uid.
SELECT uid,sum(points), date FROM users_history WHERE date BETWEEN '$start_time' AND '$end_time'" group by uid;

Comments

0
SELECT uid, SUM(points) FROM users_history WHERE date BETWEEN DATE_SUB(NOW(), INTERVAL 1 MONTH) AND NOW() GROUP BY uid

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.