我有两张表格如下:
select * from passenger_1038299
where passengerid in(select passengerid from flight_1038299
group by passengerid
having count(passengerid)>1);
问题是:
列出乘坐航班ID的乘客详细信息,该航班ID已在多个航班中旅行。 (此功能将显示乘客的详细信息及其在多个航班中旅行的航班ID。)
我使用了这个查询:
imgur.com
但它并没有给我flight_ids。请告诉我如何检索航班ID。 感谢和抱歉愚蠢的问题,作为sql的新手。
答案 0 :(得分:1)
加入航班表以获取乘客的航班
select * from passenger_1038299 p
join flight_1038299 f on f.passenger_id = p.passenger_id
where p.passengerid in(
select passengerid from flight_1038299 group by passengerid having count(passengerid)>1
);
我喜欢使用exists
来检查倍数。使用passenger_id
上的索引,它可能比上面的查询运行得更快。
select * from passenger_1038299 p
join flight_1038299 f on f.passenger_id = p.passenger_id
where exists (
select 1 from flight_1038299 f2
where f2.passenger_id = f.passenger_id
and f2.flight_id <> f.flight_id
)
修改强>
使用count
窗口函数的另一种方法:
select * from (
select *,
count() over (partition by p.passenger_id) cnt
from passenger_1038299 p
join flight_1038299 f on f.passenger_id = p.passenger_id
) t where cnt > 1
答案 1 :(得分:1)
使用分析函数的另一种方法:
SELECT * FROM (
SELECT p.*, f.flight_id,
count(*) OVER (PARTITION BY f.passenger_id ) As number_of_flights
FROM passenger p
JOIN flight f
ON p.passenger_id = f.passenger_id
)
WHERE number_of_flights > 1
答案 2 :(得分:0)
试试这种方式
航班ID应为多个,因此以逗号分隔列。
select a.*,b.flightid from passenger_1038299 a
join (select passengerid,Stuff((SELECT ', ' + s.flight_id
FROM flight_1038299 l
where c.passengerid = l.passengerid
FOR XML PATH('')),1,1,'') flightid from flight_1038299 as c group by c.passengerid having count(c.passengerid)>1) b on a.passengerid=b.passengerid