相关查询

时间:2012-11-06 05:39:55

标签: sql sql-server sql-server-2008

我有一张表,其中有一些记录如下

Model            Make            Color
==================================================
Maruti 800       2008            Black
Maruti 800       2009            White
Maruti Esteem    2000            Yelow
Maruti Esteem    2010            Red

现在我想要列表中有最大品牌的Model,Make和Color 我试过像这样编写查询

SELECT 
     Model,
     MAX(Model),
     Color
from 
     tableName
GROUP BY 
     Model,
     Color

但结果不是我想要的结果 它应该像

Model            Make            Color
===================================================
Maruti 800       2009            White    
Maruti Esteem    2010            Red

但结果是整个表格。

我只需要那些具有最大Make Model Wise的记录 我也尝试过内部查询(与co相关的查询)但是在那里它也要求分组。

1 个答案:

答案 0 :(得分:2)

以下查询支持所有RDBMS,包括MySQLOracleSQL Server,...

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  Model, MAX(Make) maxMake
            FROM tableName
            GROUP BY Model
        ) b ON a.Model = b.model AND
                a.make = b.MaxMake

如果你的RDBMS支持windows函数,

SELECT  Model, Make, Color
FROM    
        (
            SELECT  Model, Make, Color,
                    ROW_NUMBER() OVER (Partition By Model ORDER BY Make DESC) rn
            FROM tableName
        ) b 
WHERE rn = 1

WITH lists
AS
(
    SELECT  Model, Make, Color,
            ROW_NUMBER() OVER (Partition By Model ORDER BY Make DESC) rn
    FROM tableName
) 
SELECT  Model, Make, Color
FROM    lists
WHERE rn = 1