[英]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.