2012-11-06 49 views
1

我有一個表,我有一些記錄如下
corelated查詢

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的記錄。
我也試過內部查詢(合作相關的查詢)但在那也是它要求組。

回答

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 
+0

非常感謝您的回答。 –

+0

不客氣。順便說一下,你正在使用什麼數據庫服務器? –

+0

SQL Server 2008 –