繁体   English   中英

在多个连接后查找自连接中的最大值

[英]find max in self join after multiple joins

我想通过加入两个不同的表并在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数量,但当我添加后,在哪里

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

为了找到最大值,它给出了一个错误,表示table1和table2没有这样的列。

之所以我加上这个,是因为我可以确定哪个event_id的访谈次数与其他次数相比最多,但我无法找到如何做到这一点

样本数据

在您最初的自我加入之前,尝试从我认为的源数据开始工作,这会给您提供您想要的吗? 这是在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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM