人类表:
ID Name
1 Peter
2 Peter
3 Peter
4 Tom
5 Tom
6 Mary
7 Paul
如果我想在人类表中选择一个包含3次或更多次的名称,我可以这样编写查询:
Select name, count(name)
From Human
Group By name
Having count(name) >= 3
但我现在需要编写一个没有和count函数的查询。那么,如何实现这个查询?
答案 0 :(得分:4)
不是GROUP BY
,没有HAVING
,没有COUNT
- 而是双重自我join
。没有多大意义,但它确实有效!
select distinct t1.name
from tablename t1
join tablename t2 on t1.name = t2.name and t1.id <> t2.id
join tablename t3 on t1.name = t3.name and t1.id <> t3.id and t2.id <> t3.id
顺便说一句,告诉你老师你在互联网上找到了这个解决方案......
在这里演示:
答案 1 :(得分:3)
WITH cte
AS (
SELECT NAME
,SUM(1) AS NameCount
FROM Human
GROUP BY NAME
)
SELECT *
FROM cte
WHERE NameCount >= 3
或
SELECT *
FROM (
SELECT NAME
,SUM(1) AS NameCount
FROM Human
GROUP BY NAME
) MyTable
WHERE NameCount >= 3