2017-06-22 84 views
0

我有一個select返回一些行。它可能會返回1行的ID,2行的ID與最大值相同,或者沒有ID的結果。見我的選擇如下:SQL Server:從每個重複行中選擇top(Not Distinct)

SELECT e.ID, a.Type, e.Name, e.Age, e.email 
FROM  InfoEmployee e 
      INNER JOIN AnotherTable a ON a.ID = e.ID 
WHERE  a.Type in (10,15) 
ORDER BY e.ID asc, a.Type desc 

返回下面的結果,例如:

ID | Type | Name | Age | email 
100  15  John  20 [email protected] 
100  10  John  20 [email protected] 
120  15  Paul  40 [email protected] 
121  15  Marie  34 [email protected] 
121  10  Marie  34 [email protected] 
150  10  Clarie 21 [email protected] 
156  15  Mark  28 [email protected] 
156  10  Mark  28 [email protected] 

,但我想獲得:

ID | Type | Name | Age | email 
100  15  John  20 [email protected] 
120  15  Paul  40 [email protected] 
121  15  Marie  34 [email protected] 
150  10  Clarie 21 [email protected] 
156  15  Mark  28 [email protected] 

也就是說只有一排每個ID,最高的一個。 我正在尋找一個快速查詢。

我該怎麼做?

回答

1

另一種選擇是WITH TIES子句。 (沒有額外的領域)

SELECT Top 1 with Ties e.ID, a.Type, e.Name, e.Age, e.email 
FROM  InfoEmployee e 
      INNER JOIN AnotherTable a ON a.ID = e.ID 
WHERE  a.Type in (10,15) 
Order By ROW_NUMBER()OVER(Partition By e.ID Order by a.Type Desc) 
1

顯然,你只關心MAX(Type)所以才總:

SELECT e.ID, MAX(a.Type) Type, e.Name, e.Age, e.email 
FROM  InfoEmployee e 
      INNER JOIN AnotherTable a ON a.ID = e.ID 
WHERE  a.Type in (10,15) 
GROUP BY e.ID, e.Name, e.Age, e.email 
ORDER BY e.ID asc, a.Type desc 

注:看起來你只能得到MAX(Type)值,每當有兩個或多個行,例如用於Name = 'Mary'你只想要一個用Type = 15Name = 'John'相同 - 這真的是你需要的嗎?

+0

它的工作原理,但這裏的問題是,你必須組合所有的領域。 – user1624552

+0

這不是你的正確答案,它恰好適用於這種情況,但對我而言並不是很清楚你需要什麼。在這種情況下,接受的答案確實是正確的。 –

1
;With cte(ID,Type,Name,Age,email) 
AS 
(
SELECT 100,15,'John' , 20, '[email protected]' UNION ALL 
SELECT 100,10,'John' , 20, '[email protected]' UNION ALL 
SELECT 120,15,'Paul' , 40, '[email protected]' UNION ALL 
SELECT 121,15,'Marie' , 34, '[email protected]' UNION ALL 
SELECT 121,10,'Marie' , 34, '[email protected]' UNION ALL 
SELECT 150,10,'Clarie' , 21, '[email protected]' UNION ALL 
SELECT 156,15,'Mark' , 28, '[email protected]' UNION ALL 
SELECT 156,10,'Mark' , 28, '[email protected]' 
) 
SELECT ID,Type,Name,Age,email from 
(
SELECT *, ROW_NUMBER()OVER(Partition By ID Order by [Type] Desc) AS Latest from cte 
)Dt 
Where Dt.Latest=1 

輸出

ID | Type | Name | Age | email 
100  15  John  20 [email protected] 
120  15  Paul  40 [email protected] 
121  15  Marie  34 [email protected] 
150  10  Clarie 21 [email protected] 
156  15  Mark  28 [email protected]