表格:
+----+--------+------------+------+---------+-----------------+
| id | userID | difference | type | context | time |
+----+--------+------------+------+---------+-----------------+
| 83 | 111 | 30 | | | 7/15/2019 15:23 |
| 84 | 111 | 10 | | | 7/16/2019 15:28 |
| 85 | 111 | -10 | | Reset | 7/16/2020 15:28 |
| 86 | 222 | 50 | | | 7/8/2020 15:28 |
| 87 | 222 | -10 | | Reset | 7/8/2020 15:28 |
| 88 | 333 | -10 | | Reset | 5/11/2020 13:15 |
| 89 | 333 | 10 | | | 7/16/2019 13:16 |
| 91 | 111 | 20 | | | 7/17/2019 23:15 |
+----+--------+------------+------+---------+-----------------+
我正在寻找一个查询,该查询针对具有示例的MIN日期为'16 / 7/2019'的每个用户ID返还“差异”(> 0)的总和,如果该用户ID具有重置在上下文行中,必须忽略小于记录复位记录的日期的MIN日期。
所以输出应如下所示:
+--------+-------------+
| userID | SUM(points) |
+--------+-------------+
| 111 | 30|
+--------+-------------+
我的尝试:
SELECT userID, SUM(case when difference > 0 then difference else 0 end),
FROM test WHERE (CASE
WHEN (Select MAX(CAST(time as DATE)) where context ='Reset') > (Select
MIN(CAST(time as DATE))) THEN (Select MAX(CAST(time as DATE)) where
context ='Reset') ELSE (Select MIN(CAST(time as DATE))) END) = '7/16/2019' group by userID
这是表格的创建:
CREATE TABLE `test` (
`id` int(11) NOT NULL,
`userID` int(11) NOT NULL,
`difference` int(11) NOT NULL,
`type` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`context` text COLLATE utf8_unicode_ci NOT NULL,
`time` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `test` (`id`, `userID`, `difference`, `type`, `context`, `time`) VALUES
(83, 111, 30, '', '', '2019-07-15 15:23:22'),
(84, 111, 10, '', '', '2019-07-16 15:28:27'),
(85, 111, -10, '', 'Reset', '2020-07-16 15:28:27'),
(86, 222, 50, '', '', '2020-07-08 15:28:27'),
(87, 222, -10, '', 'Reset', '2020-07-08 15:28:27'),
(88, 333, -10, '', 'Reset', '2020-05-11 13:15:05'),
(89, 333, -10, '', '', '2019-07-16 13:16:35'),
(91, 111, 20, '', '', '2019-07-17 23:15:57');
答案 0 :(得分:1)
尝试类似这样的方法。为每个用户找到“重置日期”并按旧记录过滤
SELECT
t1.userId, SUM(points)
FROM
table1 t1
LEFT JOIN (
SELECT t2.userId, max(t2.date) date
FROM table2 t2
WHERE context = "Reset"
GROUP BY t2.userId
) resetDates on resetDates.userId = t1.userId
WHERE
t1.date >= IFNULL(resetDates.date, "01-01-2020")
GROUP BY
t1.userId;