1

我有一张看起来像这样的桌子

id  |  name  |  c1  |  c2  |  c3  |  c4  |  time
-------------------------------------------------
 1  |  miley |  23  |  11  |  21  |  18  |  2013-01-13 20:26:25
 2  |  john  |  31  |  29  |  23  |  27  |  2013-01-14 20:26:25
 3  |  steve |  44  |  31  |  33  |  35  |  2013-01-14 20:26:25
 4  |  miley |  34  |  44  |  47  |  48  |  2013-01-15 08:26:25
 5  |  john  |  27  |  53  |  49  |  52  |  2013-01-15 08:26:25
 6  |  steve |  27  |  62  |  50  |  64  |  2013-01-16 08:26:25
 7  |  miley |  44  |  54  |  57  |  87  |  2013-01-16 20:26:25
 8  |  john  |  37  |  93  |  59  |  62  |  2013-01-17 20:26:25
 9  |  steve |  85  |  71  |  87  |  74  |  2013-01-17 20:26:25
...etc

*注意:这是我制作的随机表格,只是为了让您了解我的表格的外观

我需要获取在特定日期范围内特定列中变化最大的人的名称。我尝试了一堆不同的查询,但无法正常工作。我认为我最接近的解决方案是......

SELECT table1.name, MAX(table1.c1-h.c1) as maxDiff 
FROM table_a as table1
LEFT JOIN table_a as table2 
ON table2.name=table1.name AND table1.c1>table2.c1
WHERE table2.c1 IS NOT NULL

我究竟做错了什么?需要明确的是,我希望能够选择一个日期范围,然后在确定的列中确定谁在该日期范围内的差异最大。另请注意,数据只会随着时间的推移而增加,因此任何一天的第一次捕获将始终 <= 该人当天的最后一次捕获。

4

2 回答 2

2

听起来您将需要一个嵌套查询。首先,查询每个人在日期范围内自己的测量值,然后按最大排序并取前 1 名……这样的事情可能对你有用……

select
      PreGroupByName.`Name`,
      PreGroupByName.MaxC1 - PreGroupByName.MinC1 as MaxSpread
   from
      ( select 
              t1.`Name`,
              min( t1.c1 ) as MinC1,
              max( t1.c1 ) as MaxC1
           from
              table_a t1
           where
              t1.`time` between '2013-01-01' and '2013-01-17'  -- or whatever date/time range
           group by
              t1.`Name` ) as PreGroupByName
   order by
      MaxSpread DESC
   limit 1
于 2013-01-24T01:25:20.137 回答
1
SELECT
    `id`,`name`
    ,MAX(`c1`)-MIN(`c1`) AS `diff_c1`
    -- ,MAX(`c2`)-MIN(`c2`) AS `diff_c2`
    -- ,MAX(`c3`)-MIN(`c3`) AS `diff_c3`
    -- ,MAX(`c4`)-MIN(`c4`) AS `diff_c4`
FROM `the_table`
WHERE `time` BETWEEN '2013-01-13 20:26:25' AND '2013-01-17 20:26:25'
GROUP BY `name`
ORDER BY `diff_c1` DESC -- whichever you want to evaluate
LIMIT 1
于 2013-01-24T01:33:55.080 回答