开发者

SQL Select Distinct Top 2

If I have a table named [Part] with columns [PartID],[IDNumber], and [Length] and data:

[PartID]  [IDNumber]  [Length]
1         Test1       50
2         Test1       60
3         Tes开发者_StackOverflowt2       50
4         Test3       70

How can I select just the top 2 records with a distinct IDNumber? After searching for a bit I have not been able to find a query that does what I want. I would like the results to look like this:

[PartID]  [IDNumber]  [Length]
1         Test1       50
3         Test2       50

What I have now:

Select distinct top 2
        [PartID],
        [IDNumber],
        [Length]
from
    [Part]

To clarify that the PartID is actually a GUID. I thought writing out the GUID for each record was getting a bit messing in my example data.


SELECT DISTINCT TOP 2 PartId, IdNumber, Length
FROM
(   SELECT PartId, IdNumber, Length, ROW_NUMBER() over(partition by IdNumber order by Length) Orden
    FROM [Ayuda]
) A
WHERE A.Orden = 1
ORDER BY Length


SELECT TOP 2 b.* 
FROM   (SELECT idnumber, 
               MIN(partid) partid 
        FROM   part 
        GROUP  BY idnumber) a 
       JOIN part b 
         ON a.partid = b.partid  
ORDER  BY b.partid 


You have not mentioned which row to select for duplicate IDNumber. From your example, assuming Min PartID is to be used, you can use the following query. It would need to be tweaked a bit.

Select Top 2
    P.*
From
    [Part] P
Inner Join
    (
        Select
             [IDNumber]
            ,Min([PartID]) As MinPartID,
        From
            [Part]
        Group By
            [IDNumber]
    ) T
On
    P.PartID = T.MinPartID
    And
    P.IDNumber = T.IDNumber -- May not be needed is PartID is primary Key
Order By
     P.[PartID]
    ,P.[IDNumber]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜