按多个排序时的不同行

时间:2018-09-03 08:52:17

标签: sql sql-server

我正在缩短查询以更好地理解。

Dim dt As New System.Data.DataTable
dt.Columns.Add(New System.Data.DataColumn("Test", System.Type.GetType("System.Data.DataTable"))) 'this is not correct

我想选择按5级顺序排序的所有不同记录。

我尝试使用 SELECT c.id, c.code, c.clientname, c.project, c.postedstate, c.postedcity, c.siteadd FROM dbo.employee c ORDER BY c.clientname, c.project, c.postedstate, c.postedcity, c.siteadd 子句,但是如果指定了SELECT DISTINCT,则由于ORDER BY项目必须出现在选择列表中而导致错误。

您能指导我解决问题吗?

实际查询:-

Distinct

1 个答案:

答案 0 :(得分:1)

请尝试使用row_number()

SELECT * FROM 
( SELECT c.id, 
       c.code, 
       c.clientname, 
       c.project, 
       c.postedstate, 
       c.postedcity, 
       c.siteadd , row_number() over (partition by clientname, project, 
          postedstate, 
          postedcity, 
          siteadd
ORDER BY clientname, project, 
          postedstate, 
          postedcity, 
          siteadd) as rn
FROM   dbo.employee )
WHERE rn=1