按组对结果进行排序

时间:2016-12-01 13:08:41

标签: sql sql-server

我有一个表,其中包含不同用户的多个重复项。我使用类似

的查询获取表中的重复项
SELECT t1.*
FROM [Database].[dbo].[table] t1
INNER JOIN
  ( SELECT [Name]
   FROM [Database].[dbo].[table]
   GROUP BY [Name]
   HAVING COUNT(*) >1 ) t2 ON t1.Name = t2.Name

从这里我从表中得到了重复的名字。我的问题是,如何将结果分组,如此

Name             Customer

John             Daydream
John             Daydream
Peter            Daydream
Peter            Daydream
Peter            Daydream
Amber            Fly_co
Amber            Fly_co
Jackie           Fly_co
Jackie           Fly_co

2 个答案:

答案 0 :(得分:0)

        SELECT t1.*
        FROM [Database].[dbo].[table] t1
        INNER JOIN
          (SELECT [Name]
                   FROM [Database].[dbo].[table]
                   GROUP BY [Name]  
                   HAVING COUNT(*) >1 ) t2 ON t1.Name = t2.Name
 ORDER BY t1.Customer, t1.Name

答案 1 :(得分:0)

试试这个......

 SELECT t1.*
    FROM [Database].[dbo].[table] t1
    INNER JOIN
      ( SELECT [Name]
       FROM [Database].[dbo].[table]
       GROUP BY t1. [Name]
       HAVING COUNT(*) >1 ) t2 ON t1.Name = t2.Name
    ORDER BY t1.Customer, t1.Name