在仅使用单一公司的客户中,找到飞行最多的不同乘客。结果集:乘客姓名,旅行次数
[详情] http://i.stack.imgur.com/cBr7E.jpg [查看此内容]
我有这个查询
SELECT P.name, COUNT(T.trip_no) AS journeys, C.name as namecompany
FROM
Passenger P, Trip T, Company C, Pass_in_trip PIT
WHERE
P.ID_psg = PIT.ID_psg AND PIT.trip_no = T.trip_no
AND T.ID_comp = C.ID_comp
AND
NOT EXISTS (SELECT * FROM
Passenger, Trip, Company, Pass_in_trip
WHERE Pass_in_trip.ID_psg = P.ID_psg AND Pass_in_trip.trip_no = Trip.trip_no
AND Trip.ID_comp <> C.ID_comp)
GROUP BY P.name, C.name;
我有这个结果集:
# name, journeys, namecompany
'Alan Rickman', '1', 'Don_avia'
'George Clooney', '1', 'Dale_avia'
'Harrison Ford', '3', 'British_AW'
'Michael Caine', '4', 'British_AW'
'Mullah Omar', '4', 'British_AW'
'Nikole Kidman', '3', 'Don_avia'
'Russell Crowe', '1', 'British_AW'
'Steve Martin', '2', 'British_AW'
我想将结果分为一个同伴一个像
# name, journeys, namecompany
'Michael Caine', '4', 'British_AW'
'Nikole Kidman', '3', 'Don_avia'
'George Clooney', '1', 'Dale_avia'
答案 0 :(得分:0)
请注意,接受的答案在技术上是错误的,因为它包含SELECT
子句中未在GROUP BY
中指定为聚合的列。以下解决方案使用两个子查询方法。第二个子查询获取每个公司的最大行程数,第一个子查询将每个公司名称与乘客连接。
另请注意,我重写了原始查询以使用显式连接,使其更易于阅读和维护。
SELECT t1.name, t2.jouneys, t2.namecompany
FROM
(
SELECT P.name, C.name AS namecompany, COUNT(T.trip_no) AS journeys
FROM Passenger P INNER JOIN Pass_in_trip PIT
ON P.ID_psg = PIT.ID_psg
INNER JOIN Trip T
ON T.trip_no = PIT.trip_no
INNER JOIN Company C
ON C.ID_comp = T.ID_comp
WHERE NOT EXISTS
(
SELECT *
FROM
Passenger, Trip, Company, Pass_in_trip
WHERE Pass_in_trip.ID_psg = P.ID_psg AND Pass_in_trip.trip_no = Trip.trip_no AND
Trip.ID_comp <> C.ID_comp
)
GROUP BY P.name, C.name
) t1
INNER JOIN
(
SELECT t.namecompany, MAX(t.journeys) AS maxJourneys
FROM
(
SELECT P.name, C.name AS namecompany, COUNT(T.trip_no) AS journeys
FROM Passenger P INNER JOIN Pass_in_trip PIT
ON P.ID_psg = PIT.ID_psg
INNER JOIN Trip T
ON T.trip_no = PIT.trip_no
INNER JOIN Company C
ON C.ID_comp = T.ID_comp
WHERE NOT EXISTS
(
SELECT *
FROM
Passenger, Trip, Company, Pass_in_trip
WHERE Pass_in_trip.ID_psg = P.ID_psg AND Pass_in_trip.trip_no = Trip.trip_no AND
Trip.ID_comp <> C.ID_comp
)
GROUP BY P.name, C.name
) t
GROUP BY t.namecompany
) t2
ON t1.namecompany = t2.namecompany AND t1.journeys = t2.maxJourneys
答案 1 :(得分:0)
在此查询中,您可以按公司名称获取最大值。试试这个
SELECT subquery.name, MAX(subquery.journeys),subquery.namecompany FROM
(
SELECT P.name, COUNT(T.trip_no) AS journeys, C.name as namecompany
FROM Passenger P, Trip T, Company C, Pass_in_trip PIT
WHERE P.ID_psg = PIT.ID_psg AND PIT.trip_no = T.trip_no
AND T.ID_comp = C.ID_comp
AND NOT EXISTS (SELECT * FROM
Passenger, Trip, Company, Pass_in_trip
WHERE Pass_in_trip.ID_psg = P.ID_psg
AND Pass_in_trip.trip_no = Trip.trip_no
AND Trip.ID_comp <> C.ID_comp)
GROUP BY P.name, C.name
)AS subquery GROUP BY subquery.namecompany;