简体   繁体   中英

Possible sybase sql query

I'm trying to get back into sql after many years away. I'm new to Sybase as well. Can you please suggest a possible query for the following problem?

There is a table called vegetables as follows.

| product | price | date     |
| beans   | 1.78  | 20040903 |
| beans   | 1.79  | 20040902 |
| potato  | 1.78  | 20040902 |

I need to get the latest available prices for each vegetable. The intended database is sybase. Many thanks.

You can use a subquery to get the max(date) for each product and then join back to your table:

select v1.product, 
  v1.price,
  v1.date
from vegetables v1
inner join
(
  select product, max(date) MaxDate
  from vegetables
  group by product
) v2
  on v1.product = v2.product
  and v1.date = v2.maxdate;

See SQL Fiddle with Demo (Demo is SQL Server but the syntax should be valid).

If your version of Sybase supports windowing functions, then you can use the following:

select product, price, date
from 
(
  select product, price, date,
    row_number() over(partition by product order by date desc) rn
  from vegetables
) v
where rn = 1;

See SQL Fiddle with Demo

From my understanding, standard SQL queries should work, for the most part, on Sybase databases. I'm no DB admin, but sometihng like this might work:

SELECT * FROM 
  vegetables v 
INNER JOIN 
  (SELECT 
      iv.id, 
      MAX(iv.date) AS date
    FROM 
      vegetables iv 
    GROUP BY 
      iv.id
  ) maxv ON maxv.date = v.date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM