[英]SQL: how to select only repeated values from same column?
!!! !!! there is a way to solve this problem using HAVING, but is there other simple way of doing it without use of HAVING ?
有一种方法可以使用HAVING解决此问题,但是还有其他简单的方法可以在不使用HAVING的情况下解决此问题吗?
let's say I have a table t1 which has got two relations a and b. 假设我有一个表t1,其中有两个关系a和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)? 如何只打印B列中重复的案例(在这种情况下:2和5)?
If you do not want a HAVING
clause, then you can use a subquery: 如果您不希望使用
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
See SQL Fiddle with Demo . 请参阅带有演示的SQL Fiddle 。
The subquery will be used to get the count of each b
value. 子查询将用于获取每个
b
值的计数。 You then join the result to your table and filter out any records that have a count greater than 1. 然后,将结果联接到表中,并过滤出计数大于1的所有记录。
This gives the result: 结果如下:
| A | B |
---------
| 1 | 2 |
| 8 | 5 |
| 5 | 2 |
| 6 | 5 |
In addition to already nice examples... Example with HAVING: 除了已经很好的示例... 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
You can do this with either aggregation or joins. 您可以使用聚合或联接来执行此操作。 I prefer the former, but here is one method:
我更喜欢前者,但这是一种方法:
select *
from t
where exists (select 1 from t t2 where t2.b = t.b and t2.a <> t.a)
This, of course, assumes that the a
values differ when the b
values are the same. 当然,这假定当
b
值相同时, a
值不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.