简体   繁体   中英

Selecting all values from row based on one distinct column

I've been browsing the forums a while trying to find a solution to my issue.

I have a table in SQL Server 2000 called result with the following data;

City       Price DepDate     RetDate
Barcelona  145   2010-05-15  2010-05-20
New York   400   2010-06-20  2010-06-20
Barcelona  160   2010-05-17  2010-05-22
New York   325   2010-05-10  2010-05-18
Istanbul   250   2010-06-22  2010-06-27

I want to query that in SQL Server 2000 so that all columns are returned but it's distinct/uniqe on the city and only the lowest price is displayed.

So i would like it to return the following

Barcelona  145   2010-05-15  2010-05-20
New York   325   2010-05-10  2010-05-18
Istanbu    250   2010-06-22  2010-06-27

I cant for my life figure out how to do this, i should be easy and I'm sure I'm going to feel dumb when the solution is presented.

Does anyone know how to do this?

Brgds, Eric

SELECT
    A1.*
FROM
    [TableName] A1
    INNER JOIN 
    (
        SELECT
            A.City
            ,   A.Price
            ,   MIN(A.DepDate) AS DepDateMin
        FROM
            [TableName] A
            INNER JOIN
            (   SELECT
                    City
                    ,   MIN(Price) AS PriceMin
                FROM
                    [TableName]
                GROUP BY City
            ) B ON A.City = B.City AND A.Price = B.PriceMin
        GROUP BY 
            A.City, A.Price
    ) B1 ON A1.City = B1.City AND A1.Price = B1.PriceMin AND A1.DepDate = B2.DepDateMin

try this one

select City,Price,DepDate,,RetDate from Your_table a 
where a.Price = (select min(Price) from Your_table b 
                where a.city = b.city group by city)

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