选择仅出现一次的那些行

时间:2016-11-18 16:39:31

标签: sql sql-server tsql

我有以下数据:

    Number  c1  c2  c3
    325     A   K   NFW
    325     U   G   GFD
    32713   A   K   fgh
    3271    U   G   ghad
    327     A   G   yrg
    3277    A   K   bfb

我不想选择那些不唯一的行。即我只想要那些具有不同“数字”列的行。我的结果应该看起来像:

    Number  c1  c2  c3
    32713   A   K   fgh
    3271    U   G   ghad
    327     A   G   yrg
    3277    A   K   bfb

我编写了以下代码,但它并没有完全正常工作:

SELECT * from [table] GROUP BY [all columns ] HAVING Count(*) = 1

任何有关获得所需结果的建议都将受到赞赏。

6 个答案:

答案 0 :(得分:9)

您还可以使用窗口聚合

WITH T
     AS (SELECT *,
                COUNT(*) OVER (PARTITION BY Number) AS C
         FROM   [table])
SELECT Number,
       c1,
       c2,
       c3
FROM   T
WHERE  C = 1 

答案 1 :(得分:5)

你几乎就在那里,只是在数字上分组。

SELECT Number, MIN(c1) AS c1, MIN(c2) AS c2, MIN(c3) AS c3
FROM [table]
GROUP BY Number
HAVING COUNT(*) = 1

答案 2 :(得分:3)

采取步骤

有哪些不同的数字?

 SELECT number
 FROM Table
 GROUP BY number
 WHERE COUNT(number) = 1

现在选择那些

SELECT *
FROM TABLE 
WHERE number in (
 SELECT number
 FROM Table
 GROUP BY number
 WHERE COUNT(number) = 1
) x

SELECT number 
FROM Table
JOIN (
 SELECT distinct number
 FROM Table
 GROUP BY number
 WHERE COUNT(number) = 1
) x on Table.number = x.number

答案 3 :(得分:1)

 select * from table where
 number in (select number from table 
       group by number 
      having count(*) = 1)

答案 4 :(得分:1)

如果表有很多记录,则存在可以做到并且比IN快。

SELECT A.Number, A.c1,  A.c2,  A.c3
FROM Table A
WHERE exists (SELECT count(1), B.number 
              FROM table B 
              WHERE B.Number = A.Number
              GROUP BY B.Number
              HAVING count(1) = 1)

答案 5 :(得分:1)

functionName(parameterName1 = value, paramterName2 = value, ...)