views:

54

answers:

2

I have a table:

mysql> desc kursy_bid;
+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| datetime  | datetime    | NO   | PRI | NULL    |       |
| currency  | varchar(6)  | NO   | PRI | NULL    |       |
| value     | varchar(10) | YES  |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

I would like to select some rows from a table, grouped by some time interval (can be one day) where I will have the first row and the last row of the group, the max(value) and min(value).

I tried:

select 
  datetime, 
  (select value order by datetime asc limit 1) open, 
  (select value order by datetime desc limit 1) close, 
  max(value),
  min(value) 
from kursy_bid_test 
  where datetime > '2009-09-14 00:00:00' 
  and currency = 'eurpln' 
group by 
  month(datetime), 
  day(datetime), 
  hour(datetime);

but the output is:

| open   | close  | datetime            | max(value) | min(value) |
+--------+--------+---------------------+------------+------------+
| 1.4581 | 1.4581 | 2009-09-14 00:00:05 | 4.1712     | 1.4581     |
| 1.4581 | 1.4581 | 2009-09-14 01:00:01 | 1.4581     | 1.4581     |

As you see open and close is the same (but they shouldn't be). What should be the query to do what I want?

A: 

It seems that the LIMIT operation is being performed before to the ORDER BY function. I'm no expert (far from it), but I'm guessing that nesting the nested query should work:

( (SELECT value ORDER BY datetime ASC) LIMIT 1) AS open

But this isn't exactly an elegant way to do it. I'm sure other SO users will have a better solution.

Zaid
A: 
SELECT DATE(datetime), 
       MIN(value) open, 
       MAX(value) close 
  FROM kursy_bid 
 WHERE DATE(datetime) = '2009-09-14' 
   AND currency = 'eurpln' 
GROUP BY DATE(datetime)

TIP: DO NOT USE KEYWORDS AS COLUMN NAMES - to zly nawyk :)

Rafal Ziolkowski
Sorry but that very away from hat i want, did you read the whole question? :)and naming coulmns with 'keywords' is not bad, doesnt make any problems :)
And - making date(datetime) = '2009-09-14' is way slower (doesn't use indexes) than datetime > '2009-09-14'
If you're going to use formatting, make it readable.
OMG Ponies