Subquery and Grouping in Sybase

It may best to describe the problem with an example:
Is it possible to query for the below data and group by fruit so that we have for each fruit, the number of times the price is quoted and the latest price (the data is sorted by time).
Table data is as below:
Fruit      Price
apple      $11
apple      $12
apple      $12.5
grape      $10
grape      $9

Result expected:
fruit -count -price
Apple 3 $12.5
grape 2 $9

Using: Sybase ASE, Embarcadero Rapid SQL is the software.
Thank you.
SeskyAsked:
Who is Participating?
 
cyberkiwiCommented:
select
 fruit,
 count(*),
 (select top 1 t2.price from mytable t2 where t2.fruit=mytable.fruit order by t2.mytime desc) as price
from mytable

If there is no time column, an ID or timestamp column will work too
0
 
DeyhimCommented:
select fruit , count(price) , sum (price) from table group by fruit
0
 
Joe WoodhousePrincipal ConsultantCommented:
Almost. "sum" is wrong here.


However we can't just say something like

     select fruit , count(price) , max(price) from table group by fruit

because we don't want the max price, we want the most recent price.

You say the data is sorted by time? Is there a time column, or do we just have to trust that it's in the right order?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.