i'm trying to find the highest number of interviews from each category (month and city) by joining two different tables and doing a self join in 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`
the above code works that shows a self join after multiple join to compare every event_id for the number of total_interviews, but when i add after where
AND table1.total_interviews > all (select table2.total_interviews FROM table2 WHERE table2.event_id <> table1.event_id)
to find the max value, it gives me an error saying there is no such column for table1 and table2.
the reason why i added this is so that i can determine which event_id has the highest number of interviews compared to the rest, but i haven't been able to find out how to do this
Trying to work back from what I think is the source data, before your initial self join, does this give you what you want? This is in 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
Result is this:
id m city
1 Jan SF
2 Feb NY
3 Mar LA
You can simply use below query.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.