具有最大条件的select子句

时间:2014-06-23 13:33:30

标签: sql oracle

对于我的数据库表:

//table1
name
---------
john
mary
ali

在我的表2中

//table2
title
---------
 test1
 test2
 test3

在我的表3中

//table3
name      title
-----------------
 john      test1
 john      test2
 john      test3
 mary      test2

所以我的问题是找到多次被名字加入的标题。

所以我的查询是:

SELECT t2.title from table2 t2 inner join table3 t3 on
   t2.title = t3.title inner join table1 t1 on 
   t1.name = t3.name having max(....)

因为我检查了一些网站。他们用于having子句的所有内容仅用于数字,我找不到任何适合我需要计算的问题的例子(*)

预期产出:

//result
title
---------
test2

2 个答案:

答案 0 :(得分:2)

按计数排序以获取从最常见标题开始的列表

SELECT t2.title 
from table2 t2 
inner join table3 t3 on t2.title = t3.title 
inner join table1 t1 on t1.name = t3.name 
group by t2.title
order by count(*) desc

要获得最佳结果,请使用

SELECT * FROM 
(
    SELECT t2.title 
    from table2 t2 
    inner join table3 t3 on t2.title = t3.title 
    inner join table1 t1 on t1.name = t3.name 
    group by t2.title
    order by count(*) desc
) X
WHERE ROWNUM = 1;

答案 1 :(得分:0)

SELECT max(name) KEEP(DENSE_RANK FIRST ORDER BY COUNT(NAME) DESC)
FROM table3
GROUP BY name