sql - 多次加入后在自加入中找到最大值
问题描述
我试图通过加入两个不同的表并在 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 与其他事件相比具有最多的采访次数,但我无法找到如何做到这一点
解决方案
在你最初的自我加入之前,试图从我认为的源数据中恢复过来,这会给你想要的吗?这是在 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
推荐阅读
- slack - 使用 slack blocks api 创建一个链接按钮
- git - 为什么 git merge commit 只能有一个父 ref?
- cypress - 在我的机器上运行功能文件的赛普拉斯问题
- css - 如何为剃刀编写带有转义字符的动态内部css?
- ocr - OCR - tesseract - 提取表格数据中的数字
- android - 如何使用 bridgefy SDK 发送离线广播消息?
- jquery - 发出 AJAX 请求后表格不显示数据
- matlab - Matlab 向量化与 if 和 for 循环使用 ODE45 集成
- jenkins - 无法使用詹金斯声明性管道执行 ansible 剧本
- c++ - 如何在常量评估表达式中获得编译时错误?