0

!!! there is a way to solve this problem using HAVING, but is there other simple way of doing it without use of HAVING ?

let's say I have a table t1 which has got two relations a and b.

-a  b
-1  2
-2  1
-3  4
-4  9
-8  5
-5  2
-6  5

how do I print only the cases from column B that are repeating (in this case: 2 and 5)?

4

3 回答 3

4

如果您不想要HAVING子句,则可以使用子查询:

select t1.a, t1.b
from yourtable t1
inner join
(
  select count(*) tot, b
  from yourtable
  group by b
) t2
  on t1.b = t2.b
where t2.tot > 1

请参阅SQL Fiddle with Demo

子查询将用于获取每个b值的计数。然后将结果连接到表中并过滤掉计数大于 1 的任何记录。

这给出了结果:

| A | B |
---------
| 1 | 2 |
| 8 | 5 |
| 5 | 2 |
| 6 | 5 |
于 2013-02-06T16:51:25.093 回答
2

除了已经很好的例子...... HAVING的例子:

SELECT * FROM 
(
 SELECT col_a t1
   FROM stack_test
 ) a,
 (
 SELECT col_b t2
   FROM stack_test
  GROUP BY col_b
  HAVING Count(*) > 1
 ) b
 WHERE t1 = t2
 /

 SQL>

  T1   T2
  -------
  2     2
  5     5
于 2013-02-06T17:36:05.570 回答
0

您可以使用聚合或联接来执行此操作。我更喜欢前者,但这里有一种方法:

select *
from t
where exists (select 1 from t t2 where t2.b = t.b and t2.a <> t.a)

当然,这假设当a值相同时值不同b

于 2013-02-06T16:52:20.230 回答