在多次加入后在自我加入中找到最大值

时间:2019-05-30 00:12:42

标签: sql self-join

我试图通过联接两个不同的表并在sql中进行自我联接来找到每个类别(月和城市)中最多的采访次数

`select distinct table1.event_id, table1.month, table1.city

from

(SELECT event_id, count(*) as total_interviews, month, city
FROM company, events
where company.interviewee_id = events.interviewee_id
GROUP BY event_id, month, city) as table1,

(SELECT event_id, count(*) as total_interviews, month, city
FROM company, events
where company.interviewee_id = events.interviewee_id
GROUP BY event_id, month, city) as table2 

WHERE table1.event_id <> table2.event_id
AND table1.month = table2.month
AND table1.city = table2.city`

上面的代码可以显示多次连接后的自我连接,以比较每个event_id与total_interviews的数量,但是当我在where之后添加

AND table1.total_interviews > all (select table2.total_interviews FROM table2 WHERE table2.event_id <> table1.event_id) 

要找到最大值,它给我一个错误,指出table1和table2没有这样的列。

我添加此内容的原因是为了可以确定哪个event_id与其他采访相比具有最高的采访数量,但是我一直无法找出如何做到这一点

sample data

2 个答案:

答案 0 :(得分:0)

在我最初的自我加入之前,尝试根据我的 源数据进行工作,这是否能为您提供所需的信息?这是在sql server中。

N

结果是这样的:

declare @i table(id int, n int, m varchar(30), city varchar(2))
insert @i values (1,4,'Jan','SF')
,(2,5,'Feb','NY')
,(3,6,'Mar','LA')
,(4,3,'Jan','SF')
,(5,2,'Feb','NY')
,(6,1,'Mar','LA')

;with cte as (
    select *, row_number() over(partition by m,city order by n desc) roworder 
    from @i
)
select id,m,city from cte 
where roworder=1 
order by id

答案 1 :(得分:0)

您可以简单地使用以下查询。

SELECT * FROM (
    SELECT EventID,total_interviews, Month, City, row_number() over(partition by event_ID,month, City order by total_interviews DESC) as RN
    FROM (
       SELECT Company.event_id, count(*) as total_interviews, Events.month, Events.city, 
       FROM company, events
       where company.interviewee_id = events.interviewee_id
       GROUP BY Company.event_id, Events.month, Events.city 
       ) A
    ) B where RN = 1