T-SQL SELECT TOP 1 DISTINCT重复

时间:2016-07-05 21:40:49

标签: sql sql-server tsql

除了查询中的零之外,我只需要返回每个重复数字的第一行:

DECLARE @Test TABLE 

(
ID NVARCHAR(10)
,Number INT

)
INSERT INTO @Test VALUES ('TG32',6)
INSERT INTO @Test VALUES ('TG47',6)
INSERT INTO @Test VALUES ('AG9',6)
INSERT INTO @Test VALUES ('BF27',2)
INSERT INTO @Test VALUES ('QD65',2)
INSERT INTO @Test VALUES ('F98',0)
INSERT INTO @Test VALUES ('GC5',0)
INSERT INTO @Test VALUES ('HT76',0)
INSERT INTO @Test VALUES ('KL81',0)
INSERT INTO @Test VALUES ('WR52',0)

 SELECT * FROM @Test

我试图获得:

身份证号码

TG32    6
BF27    2
F98     0
GC5     0
HT76    0
KL81    0
WR52    0

3 个答案:

答案 0 :(得分:2)

假设您的ID列已订购,您可以对数字进行分组并获得最小值ID但排除数字= 0的行,然后将数字为0的行合并。这些query实现的是:

SELECT MIN(id) as ID -- get the minimum value in a group
     , number        -- the nmber for the group
FROM @test
WHERE number <> 0    -- but leave out rows where number is zero
GROUP BY number      -- get those together
UNION                -- add all the other rows
SELECT id
     , number
FROM @test
WHERE number = 0     -- that have a number that is zero

结果是:

BF27 2
AG9  6
F98  0
GC5  0
HT76 0
KL81 0
WR52 0

答案 1 :(得分:0)

您可以使用ROW_NUMBER和子查询进行此操作。

SELECT ID, Number
FROM (
    SELECT  *, 
            ROW_NUMBER() OVER (PARTITION BY Number ORDER BY (SELECT 1))as RN
    FROM @test) as d
WHERE (CASE WHEN d.Number = 0 THEN 1 ELSE d.RN END) = 1

您还可以使用另一个WHERE语句

WHERE d.Number = 0 OR d.RN = 1

使用CTE:

 ;WITH cte as (
 SELECT  *, 
         ROW_NUMBER() OVER (PARTITION BY Number ORDER BY (SELECT 1))as RN
 FROM @test)

 SELECT ID, Number
 FROM cte
 WHERE Number = 0 or RN = 1

答案 2 :(得分:-1)

做这样的事情:

 SELECT DISTINCT * FROM @Test

希望有所帮助。