SQL . Timestamp issue with max value

假装没事ソ 提交于 2019-12-25 00:52:53

问题


Hello I have a sql script like this. My intention of the script is to produce out the highest value of today. However the script produce out an unintended result. Can anyone help me look at my code and see what is wrong with it ?

Script

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;

The Unintended Result

Value Timestamp    fooditem   cashcurren

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

The Result I want

Value Timestamp fooditem cashcurren

 536 1406034973          2         10

Basically I want my Oracle SQL to return back the highest value for food item #2 and cashcurrency #10 from the timestamp 1405987200 to 1405987200 + 86400 (the timestamp is the whole day of 7/22 in this case).


回答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)

Using max(value) and grouping by timestamp does not lead to any aggregation and does not make sense. (there is likely only one per timestamp)

The above query uses a subquery to select the max value for the given timestamp range, fooditem, and cashcurren, and then feeds that value to the query in the where clause.




回答2:


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;



回答3:


    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;


来源:https://stackoverflow.com/questions/24897127/sql-timestamp-issue-with-max-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!