SQL Server:从每个重复行中选择顶部(不区分)

时间:2017-06-22 12:30:51

标签: sql-server sql-server-2008 sql-server-2008-r2

我有一个返回一些行的选择。它可以为ID返回1行,为最大相同ID返回2行,或者ID不返回任何结果。请参阅下面的选择:

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    john@mail.com
100      10      John      20    john@mail.com
120      15      Paul      40    paul@mail.com
121      15      Marie     34    marie@mail.com
121      10      Marie     34    marie@mail.com
150      10      Clarie    21    clarie@mail.com
156      15      Mark      28    mark@mail.com
156      10      Mark      28    mark@gmail.com

但我想获得:

ID   |   Type  | Name    | Age | email
100      15      John      20    john@mail.com
120      15      Paul      40    paul@mail.com
121      15      Marie     34    marie@mail.com
150      10      Clarie    21    clarie@mail.com
156      15      Mark      28    mark@mail.com

每个ID只有一行,最重要的一行。 我正在寻找快速查询。

我该怎么做?

3 个答案:

答案 0 :(得分: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 = 15的{​​{1}}并且Name = 'John'相同1}} - 这真的是你需要的吗?

答案 1 :(得分:1)

;With cte(ID,Type,Name,Age,email)
AS
(
SELECT 100,15,'John'   ,  20,   'john@mail.com'   UNION ALL
SELECT 100,10,'John'   ,  20,   'john@mail.com'   UNION ALL
SELECT 120,15,'Paul'   ,  40,   'paul@mail.com'   UNION ALL
SELECT 121,15,'Marie'  ,  34,   'marie@mail.com'  UNION ALL
SELECT 121,10,'Marie'  ,  34,   'marie@mail.com'  UNION ALL
SELECT 150,10,'Clarie' ,  21,   'clarie@mail.com' UNION ALL
SELECT 156,15,'Mark'   ,  28,   'mark@mail.com'   UNION ALL
SELECT 156,10,'Mark'   ,  28,   'mark@gmail.com'
)
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    john@mail.com
120      15      Paul      40    paul@mail.com
121      15      Marie     34    marie@mail.com
150      10      Clarie    21    clarie@mail.com
156      15      Mark      28    mark@mail.com

答案 2 :(得分: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)