删除重复的结果

时间:2016-12-10 10:45:12

标签: sql sql-server-2008 select view

我有一些记录,其中许多是重复的。我需要过滤记录并从每个记录中只获取一个记录。

我已经尝试了

SELECT TOP 1 Item, Code, Desc, '1' AS Qty FROM vwTbl1 WHERE Code = '12' OR Code = '311'

还尝试使用DISTINCT,但我仍然可以获得所有记录。

但在这种情况下它只显示一条记录。按代码分组并不起作用。 有没有其他方法可以解决这个问题?

    Item | Code   | Desc | QTY  
 a       |   12   |  1   |1
 a       |   311  |  2   |1
 b       |   12   |  3   |1
 b       |   311  |  4   |1
 c       |   1    |  5   |1   

Reult应该像:

    Item | Code   | Desc | QTY  
 a       |   12   |  1   |1
 b       |   311  |  3   |1  

因此,每个标准都获得第一条记录。

2 个答案:

答案 0 :(得分:1)

执行此操作的典型方法是使用row_number()

SELECT TOP 1 Item, Code, Desc, 1 AS Qty
FROM (SELECT v.*,
             ROW_NUMBER() OVER (PARTITION BY Code ORDER BY (SELECT NULL)) as seqnum
      FROM vwTbl1 
      WHERE Code IN ('12', '311') -- don't use single quotes if these are numbers
     ) v
WHERE seqnum = 1;

答案 1 :(得分:0)

SELECT Top 1 *
FROM 
(
  SELECT Item, Code, Desc, '1' AS Qty 
  FROM vwTbl1 WHERE Code = '12' OR Code ='311'
)A

Edited Code based on your expected result:

Declare @YourTable table (Id INT IDENTITY(1,1),Item varchar(50),Code INT,       
_Desc INT,Qty INT)
 Insert into @YourTable
 SELECT 'a',12,1,1 UNION ALL
 SELECT 'a',311,2,1 UNION ALL
 SELECT 'b',12,3,1 UNION ALL
 SELECT  'b',311,4,1 UNION ALL
 SELECT  'c',1 ,5 ,1   

 SELECT Item ,A.Code , _Desc ,Qty
 FROM @YourTable T
 JOIN 
 (
  SELECT MAX(Id) Id, Code FROM @YourTable GROUP BY Code
 )A ON A.Id = T.Id