0

表模式设置如下:

userID      Points       timestamp

1           40
3           20
1           10
4           15
3           5

需要能够提供显示以下内容的报告:

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

我尝试了以下,你可以看到不正确

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

3 回答 3

2

假设您有值作为时间戳,我将使用列名 userid、points 和 time_stamp 以及 userpoints 的表名:

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

所以:

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

会导致:

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

更新:针对 UNIX 问题进行了改进

SELECT userID,
       sum(points),
       from_unixtime(timestamp, 'DD-MM-YYYY') as date
FROM   userpoints
GROUP BY userID, date(timestamp)
于 2010-08-18T17:58:38.957 回答
2

MySQL 没有递归功能,因此您只能使用 NUMBERS 表技巧来获取天数列表,以便通过 LEFT JOIN 来查看归因于零关系的天数。

  1. 创建一个只包含递增数字的表 - 使用 auto_increment 很容易做到:

    DROP TABLE IF EXISTS `example`.`numbers`;
    CREATE TABLE  `example`.`numbers` (
      `id` int(10) unsigned NOT NULL auto_increment,
       PRIMARY KEY  (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
  2. 使用以下方法填充表:

    INSERT INTO NUMBERS
      (id)
    VALUES
      (NULL)
    

    ...根据需要获取尽可能多的值。

  3. 使用DATE_ADD构造时间列表,根据 NUMBERS.id 值增加月份:

    SELECT x.*
      FROM (SELECT DATE_ADD('2010-01-01', INTERVAL n.id - 1 DAY)
              FROM numbers n) x
    
  4. LEFT JOIN 根据日期时间部分加入您的数据表:

       SELECT up.userid,
              COALESCE(SUM(up.points), 0) AS points
              DATE(x.dt) AS date
         FROM (SELECT DATE_ADD('2010-01-01', INTERVAL n.id - 1 MONTH) AS dt
                 FROM numbers n) x
    LEFT JOIN USERPOINTS up ON DATE(FROM_UNIXTIME(up.timestamp)) = DATE(x.dt)
     GROUP BY up.userid, DATE(x.dt)
    
于 2010-08-18T18:12:33.207 回答
1
SELECT DATE(time_stamp) as date1, userID, SUM(Points) as total_points
FROM table1
GROUP BY date1, userID
WITH ROLLUP

用户 ID 为空且 date1 不为空的记录显示在该日期分配了多少点,用户 ID 为空且 date1 为空的记录 - 分配的总点数。

于 2010-08-18T18:00:36.340 回答