从只有一个不同的colum SQL的重新出现中选择一个副本

时间:2017-03-24 06:59:11

标签: sql duplicates sybase

Current State
id | val | varchar_id| uid
----------------------
1  | 1   |  A4D        NEWID()
1  | 2   |  A3G        NEWID()
2  | 1   |  7S3        NEWID()
2  | 1   |  43E        NEWID()
2  | 2   |  7S3        NEWID()
2  | 2   |  431        NEWID()
3  | 1   |  432        NEWID()
3  | 2   |  43P        NEWID()

Ideal state
id | val | varchar_id|
----------------------
1  | 1   |  A4D        NEWID()
1  | 2   |  A3G        NEWID()
2  | 1   |  7S3        NEWID()
2  | 2   |  7S3        NEWID()
3  | 1   |  432        NEWID()
3  | 2   |  43P        NEWID()

删除重复出现的id + val

我试过(下面的伪代码):

SELECT *
from table 
WHERE uid = MAX
GROUP BY id, val

有没有人知道这个的解决方案/我在这里遗漏了什么?我不介意返回哪些重复项。

此外,我使用的Sybase版本不允许分区x超过x,y功能。

1 个答案:

答案 0 :(得分:4)

使用SQL可以这样做。你的where子句也不是SQL支持的。

DECLARE @T TABLE (ID INT, Val INT, V_ID VARCHAR(50), uidd UNIQUEIDENTIFIER)
INSERT INTO @T VALUES
(1,1,'A4D',NEWID()),
(1,2,'A3G',NEWID()),
(2,1,'7S3',NEWID()),
(2,2,'43E',NEWID()),
(2,2,'7S3',NEWID()),
(2,2,'431',NEWID()),
(3,1,'432',NEWID()),
(3,2,'43P',NEWID())

SELECT t.id, t.Val, MAX(V_ID) AS varchar_id, MAX(uidd) 
FROM @T AS t 
GROUP BY id, val
ORDER BY id, val

这将为您提供结果

+---+----+-----------+-------------------------------------+
|id |Val |varchar_id |uid                                  |
+---+----+-----------+-------------------------------------+
|1  |1   |A4D        |5296ACE4-573A-4A7E-882F-516EA8E9DBDD |
|1  |2   |A3G        |3EE82BEE-8C18-4415-BB3D-110F443409B5 |
|2  |1   |7S3        |68DBF7B3-316D-4A8B-B8AD-8825EC83585D |
|2  |2   |7S3        |01C54277-7156-47E1-9205-DD577A726196 |
|3  |1   |432        |6F53F332-FC9C-4EE1-A3D2-1D0FD002DDAF |
|3  |2   |43P        |7B532EBD-E6C9-4BE4-B0F7-FCBCB9CE1D61 |
+---+----+-----------+-------------------------------------+