如果我有一个名为[Part]的表,列[PartID],[IDNumber]和[Length]和数据:
[PartID] [IDNumber] [Length]
1 Test1 50
2 Test1 60
3 Test2 50
4 Test3 70
如何只选择具有不同IDNumber的前2条记录?在搜索了一下后,我找不到能够做我想要的查询。我希望结果看起来像这样:
[PartID] [IDNumber] [Length]
1 Test1 50
3 Test2 50
我现在拥有的:
Select distinct top 2
[PartID],
[IDNumber],
[Length]
from
[Part]
澄清PartID实际上是GUID。我认为写出每个记录的GUID在我的示例数据中有点混乱。
答案 0 :(得分:48)
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
答案 1 :(得分:4)
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
答案 2 :(得分:1)
您没有提到要为重复的IDNumber选择哪一行。在您的示例中,假设要使用Min PartID,您可以使用以下查询。需要稍微调整一下。
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]