表架构设置如下:
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
答案 0 :(得分:2)
假设您有值作为时间戳,我将使用列名userid,points和time_stamp以及用户点的表名:
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)
答案 1 :(得分:2)
MySQL没有递归功能,所以你可以使用NUMBERS表技巧来获取一个天数列表,以便在看到零关系归属的日子之前联系起来。
创建一个只保存递增数字的表 - 使用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;
使用以下方法填充表格:
INSERT INTO NUMBERS
(id)
VALUES
(NULL)
...根据需要提供尽可能多的价值。
使用DATE_ADD构建一个时间列表,根据NUMBERS.id值增加月份:
SELECT x.*
FROM (SELECT DATE_ADD('2010-01-01', INTERVAL n.id - 1 DAY)
FROM numbers n) x
根据日期时间部分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)
答案 2 :(得分:1)
SELECT DATE(time_stamp) as date1, userID, SUM(Points) as total_points
FROM table1
GROUP BY date1, userID
WITH ROLLUP
具有null userID而非null date1的记录显示在该日期分配了多少个点, 具有null userID和null date1的记录 - 分配的总分数。