1

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

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

现在我想要列表中具有最大品牌的型号、品牌和颜色。
我试过写这样的查询

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 的记录。
我也尝试过内部查询(共同相关查询),但它也要求分组依据。

4

1 回答 1

2

下面的查询支持所有 RDBMS,包括MySQL, Oracle, SQL 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
于 2012-11-06T05:41:52.037 回答