在2列上选择distinct,但从SQL Server返回所有列

时间:2017-08-04 19:36:36

标签: sql sql-server

有没有办法在2列上选择不同但返回所有列?

例如

select distinct name, type 
from dbo.Table

但返回dbo.Table的所有列?

我发现这个解决方案适用于单个列,

SELECT 
    * 
FROM
    (SELECT
         [name], [type],
         [col1], [col2], [col3],
         [etc], [dateAdded], [ID],
         ROW_NUMBER() OVER (PARTITION BY type ORDER BY dateAdded DESC) rownumber 
     FROM 
         [dbo].[Table]) a 
WHERE
    rownumber = 1;

可以为多个列执行此操作吗?

1 个答案:

答案 0 :(得分:3)

您可以按名称和类型使用分区,如下所示


SELECT * from(select 
   [name]
  ,[type]
  ,[col1]
  ,[col2]
  ,[col3]
  ,[etc]
  ,[dateAdded]
  ,[ID]
  ,ROW_NUMBER() OVER(Partition by name, type order by dateAdded DESC) rownumber from [dbo].[Table]) a where rownumber = 1;