Search code examples
sqlmysqlaggregate-functionsdatetime-generation

Need help with a MYSQL query grouping


Table schema is set up something like this:

userID      Points       timestamp

1           40
3           20
1           10
4           15
3           5

Need to be able to present a report that shows the following:

Total Points Allocated for the Day (0 if none allocated), (nice to have) To what userID's the points were allocated to for that day

I tried the following and well as you can see is not correct

SELECT uid, DATE(time_stamp) AS date, SUM(points) AS total_points
FROM table
GROUP BY date

Solution

  • Assuming you had values as the timestamp, and I'll use the column names userid, points and time_stamp and a table name of userpoints:

    SELECT userID,
           sum(points),
           date(timestamp) as date
    FROM   userpoints
    GROUP BY userID, date(timestamp)
    

    So:

    userID      Points       timestamp 
    
    1           40           18-8-2010 12:00:00.000
    3           20           18-8-2010 12:00:00.000
    1           10           18-8-2010 12:00:00.000
    4           15           18-8-2010 12:00:00.000
    3           5            18-8-2010 12:00:00.000
    

    Would result in:

    userid      points       date
    1           50           18-8-2010
    3           25           18-8-2010
    4           15           18-8-2010
    

    UPDATE: Refined for UNIX Issue

    SELECT userID,
           sum(points),
           from_unixtime(timestamp, 'DD-MM-YYYY') as date
    FROM   userpoints
    GROUP BY userID, date(timestamp)