我有两个描述用户及其付款的表格:
CREATE TABLE test_users
(id int IDENTITY NOT NULL,
name varchar(25),
PRIMARY KEY (id));
CREATE TABLE test_payments
(id int IDENTITY NOT NULL,
user_id int NOT NULL,
money money NOT NULL,
date datetime NOT NULL,
PRIMARY KEY (id));
INSERT INTO test_users (name)
VALUES ('john');
INSERT INTO test_users (name)
VALUES ('peter');
INSERT INTO test_payments (user_id, money, date)
VALUES (1, $1, CONVERT(datetime, '15.12.2012'));
INSERT INTO test_payments (user_id, money, date)
VALUES (1, $2, CONVERT(datetime, '16.12.2012'));
INSERT INTO test_payments (user_id, money, date)
VALUES (2, $1, CONVERT(datetime, '16.12.2012'));
INSERT INTO test_payments (user_id, money, date)
VALUES (2, $3, CONVERT(datetime, '17.12.2012'));
INSERT INTO test_payments (user_id, money, date)
VALUES (1, $1, CONVERT(datetime, '19.12.2012'));
表 test_users:
id name
-------------
1 john
2 peter
表 test_payments:
id user_id money last_activity
---------------------------------------
1 1 1.0000 2012-12-15
2 1 2.0000 2012-12-16
3 2 1.0000 2012-12-16
4 2 3.0000 2012-12-17
5 1 1.0000 2012-12-19
我需要制作一个用户统计数据,它会告诉我:
- 用户名
- 一段时间内的总费用
- 最后一个用户活动的日期(一般,不是一段时间)。
例如,以 15-18.12.12 期间为例,我期望得到以下结果:
name total last_activity
--------------------------------
peter $4 2012-12-17
john $3 2012-12-19
我尝试了以下查询:
SELECT u.*, SUM(p.money) total, MAX(p.date) last_activity
FROM test_users u
JOIN test_payments p
ON u.id= p.user_id
WHERE p.date BETWEEN CONVERT(datetime, '15.12.2012') AND CONVERT(datetime, '18.12.2012')
GROUP BY u.id, u.name
ORDER BY total DESC;
但 last_activity 的结果错误,因为它也在日期范围内:
id name total last_activity
--------------------------------
2 peter 4.0000 2012-12-17
1 john 3.0000 2012-12-16
请提出解决方案。