2014-07-22 71 views
0

你好,我有一个像这样的SQL脚本。我的意图是产生今天最高的价值。然而,剧本产生了意想不到的结果。任何人都可以帮我看看我的代码,看看它有什么问题吗?SQL。最大值的时间戳问题

脚本

SELECT MAX(Value), 
     TIMESTAMP, 
     fooditem, 
     cashcurren 
FROM  farm1 
WHERE r.timestamp > 1405987200 
     AND r.timestamp <= (1405987200 + 86400) 
     AND fooditem = '2' 
     AND cashcurren = '10' 
GROUP BY timestamp, fooditem, cashcurren; 

意外结果

Value Timestamp fooditem cashcurren 

200 1406029354   2   10 
    84 1406034965   2   10 
536 1406034973   2   10 
    70 1406035006   2   10 
    63 1406035025   2   10 

我想要的结果

值时间戳fooditem cashcurren

536 1406034973   2   10 

基本上我想要我的Oracle SQL来将时间戳1405987200至1405987200 + 86400的食品项目#2和现金货币#10的最高值返回(在这种情况下,时间戳是7/22的全天)。

+0

如果你看看结果,每一行都有不同的时间戳。您为每个时间戳,fooditem和cashcurren组合选择了最大值(您的group by子句全部为3)。你有5行而不是1的原因是因为这5行中的每一行都有不同的时间戳。您按时间戳分组。您可以改为按值降序进行聚合和排序,限制1或使用带内联视图的联接或使用子查询。 –

回答

1
SELECT Value, TIMESTAMP, fooditem, cashcurren 
    FROM farm1 f 
WHERE timestamp between 1405987200 and (1405987200 + 86400) 
    AND fooditem = '2' 
    AND cashcurren = '10' 
where value = 
     (select max(x.value) 
      from farm1 x 
     where x.timestamp between 1405987200 and (1405987200 + 86400) 
      and x.fooditem = f.fooditem 
      and x.cashcurren = f.cashcurren) 

使用MAX(值)和分组通过时间戳不会导致任何聚集,没有任何意义。 (每个时间戳可能只有一个)

以上查询使用子查询为给定时间戳范围fooditem和cashcurren选择最大值,然后将该值提供给where子句中的查询。

0
SELECT MAX(Value), 
     TIMESTAMP, 
     fooditem, 
     cashcurren 
FROM  farm1 
WHERE r.timestamp > 1405987200 
     AND r.timestamp <= (1405987200 + 86400) 
     AND fooditem = '2' 
     AND cashcurren = '10' 
GROUP BY timestamp, fooditem, cashcurren 
order by 1 desc limit 1; 
0
SELECT d.Value, d.TIMESTAMP, d.fooditem, d.cashcurren 
    FROM  (SELECT MAX(Value) AS 'Value', 
        TIMESTAMP, 
        fooditem, 
        cashcurren 
      FROM  farm1 
      WHERE r.timestamp > 1405987200 
        AND r.timestamp <= (1405987200 + 86400) 
        AND fooditem = '2' 
        AND cashcurren = '10' 
      GROUP BY timestamp, fooditem, cashcurren) AS d 
    ORDER BY d.Valuse DESC limit 1;