首页 > 解决方案 > 多次加入后在自加入中找到最大值

问题描述

我试图通过加入两个不同的表并在 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 的总数,但是当我在 where 之后添加时

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

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

我添加这个的原因是我可以确定哪个 event_id 与其他事件相比具有最多的采访次数,但我无法找到如何做到这一点

样本数据

标签: sqlself-join

解决方案


在你最初的自我加入之前,试图从我认为的源数据中恢复过来,这会给你想要的吗?这是在 sql server 中。

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

结果是这样的:

id  m   city
1   Jan SF
2   Feb NY
3   Mar LA

推荐阅读