返回一次只出现一次的column1值的查询

时间:2017-10-02 10:06:58

标签: sql database plsql

我们有一个这样的表:

|---------------------|------------------|
|      column1        |     column2      |
|---------------------|------------------|
|          A          |         1234     |
|---------------------|------------------|
|          A          |         6666     |
|---------------------|------------------|
|          A          |         7777     |
|---------------------|------------------|
|          B          |         1234     |
|---------------------|------------------|
|          B          |         6666     |
|---------------------|------------------|
|          C          |         6666     |
|---------------------|------------------|
|          D          |         1234     |
|---------------------|------------------|

我想要一个返回C和D的查询。

我想要一个返回column1中少于2次的值的查询(编辑:在“只有一次”之后)。

我正在使用plSQL。

我试过这个:

SELECT * 
FROM myTable
GROUP BY columnNeeded
HAVING COUNT(*) < 2;

5 个答案:

答案 0 :(得分:1)

尝试使用distinct:

SELECT column1 
FROM myTable
GROUP BY column1
HAVING COUNT(column1) < 2;

答案 1 :(得分:1)

select中的列列表应与GROUP BY中的列列表匹配,当您在*中指定单个列时,不应使用GROUP BY,否则您需要在columns子句中指定所有group by

SELECT column1 
FROM myTable
GROUP BY column1
HAVING COUNT(column1) < 2;

答案 2 :(得分:1)

您的查询没问题,但您无法选择所有列(仅在group by子句中出现,除非......)。因此,您需要max(column2),无论如何都是唯一的:

SELECT columnNeeded, max(column2)
FROM myTable
GROUP BY columnNeeded
HAVING COUNT(*) = 1;

答案 3 :(得分:0)

使用CTE

;WITH yourtable AS
(SELECT *, COUNT(*) OVER (PARTITION BY column1) AS col1count FROM mytable)
SELECT column1, column2
FROM yourtable
WHERE col1count = 1

输出

column1 column2
C       6666
D       1234

SQL小提琴:http://sqlfiddle.com/#!15/2fd7f/1/0

答案 4 :(得分:0)

您需要做的就是按列1分组,然后使用“having”子句过滤结果,就像这样:

WITH MY_TABLE AS(
  SELECT 'A' AS COLUMN1, 1234 AS COLUMN2 FROM DUAL UNION ALL
  SELECT 'A' AS COLUMN1, 6666 AS COLUMN2 FROM DUAL UNION ALL
  SELECT 'A' AS COLUMN1, 7777 AS COLUMN2 FROM DUAL UNION ALL
  SELECT 'B' AS COLUMN1, 1234 AS COLUMN2 FROM DUAL UNION ALL
  SELECT 'B' AS COLUMN1, 6666 AS COLUMN2 FROM DUAL UNION ALL
  SELECT 'C' AS COLUMN1, 6666 AS COLUMN2 FROM DUAL UNION ALL
  SELECT 'D' AS COLUMN1, 1234 AS COLUMN2 FROM DUAL
)
SELECT    COLUMN1 
FROM      MY_TABLE
GROUP BY  COLUMN1
HAVING    COUNT(COLUMN1) < 2;