需要帮助找出排序SQL查询

时间:2019-03-06 08:19:18

标签: mysql sql

我正在尝试从这种表格中获得或失去的关卡总数:

id   name   level   timestamp
1    Rex      15       10:25
2    Rex      15       10:26
3    Rex      15       10:27
4    Rex      14       10:28
5    Rex      13       10:29
6    Rex      13       10:30
7    Rex      13       10:31
8    Rex      13       10:29
9    Xer      44       10:30
10   Xer      44       10:31
11   Xer      45       10:32
12   Xer      45       10:33
13   Xer      45       10:34

目前我正在跑步

SELECT id, name, level, timestamp, MAX(level) - MIN(level) AS gained
FROM log
GROUP BY name

但是此查询的问题在于,获得和失去的水平都将视为获得。如果用户丢失了级别,如果在获得的列中得到负整数,那将是完美的选择

我想从上面的数据中得到的输出是:

id   name   level   timestamp   gained
8    Rex     13       10:29      -2
13   Xer     45       10:34       1

2 个答案:

答案 0 :(得分:1)

如果您需要遵守时间表,请尝试执行以下操作:

SELECT MAX(id) id, name,
       ( SELECT level FROM log l0 WHERE l.name = l0.name ORDER BY timestamp DESC LIMIT 1 ) level,
       MAX(timestamp) timestamp,
       -- last entry for the name
       ( SELECT level FROM log l1 WHERE l.name = l1.name ORDER BY timestamp DESC LIMIT 1 ) -
       -- first entry for the name
       ( SELECT level FROM log l2 WHERE l.name = l2.name ORDER BY timestamp ASC LIMIT 1 ) gained
FROM log l
GROUP BY name

答案 1 :(得分:0)

我使用LAG作为子查询来获取更改,然后将这些更改汇总到外部子查询中。为了获得最后一行,我使用了另一个查询来查找每个名称的最长时间。也许不是最有效的查询,但它可以工作

SELECT l.id, l.name, l.level, l.timestamp, sg.gain
FROM log l
JOIN (SELECT name, SUM(gain) gain
      FROM (SELECT name, level - COALESCE(LAG(level) OVER w, level) as gain
            FROM log
            WINDOW w AS (PARTITION BY name ORDER BY timestamp)) as g
      GROUP BY name) as sg ON sg.name = l.name
JOIN (SELECT name, MAX(time) max_t
      FROM log
      GROUP BY name) mt ON mt.name = l.name AND mt.max_t = l.time