如何获得最大数量的旅行

时间:2012-11-10 16:38:30

标签: sql oracle11g

查找执行最多行程的所有司机的许可证号码(LicenseCardNo)。我无法编写SQL select语句来实现此目的。如果你们能帮忙,我们将不胜感激。以下是关于我的表格和表格内的值的示例数据?我还附上了迄今为止我所做的代码。

 DRIVER(OwnerNo, LicenseCardNo,STATUS,)
 PRIMARY KEY(OwnerNo)
 UNIQUE(LicenseCardNo)
 FOREIGN KEY(OwnerNo) REFERENCES EMPLOYEE(OwnerNo)
 CHECK ( STATUS IN ('MAIN DRIVER', 'DRIVER', 'TAXI DRIVER')) )

 ( A29, DR1, 'MAIN DRIVER' )
 ( A28, DR2, 'MAIN DRIVER' )
 ( A25, DR3, 'TAXI DRIVER' )
 ( A25, DR22, 'DRIVER' )
 ( A20, DR6, 'DRIVER' )
 ( A23, DR7, 'TAXI DRIVER' )
 ( A30, DR8, 'TAXI DRIVER' )

TRIP( TripNo,LicenseCardNo,CarReg,TRIP_DATE,)
PRIMARY KEY (TripNo),
FOREIGN KEY (LicenseCardNo) REFERENCES DRIVER(LicenseCardNo),
FOREIGN KEY (CarReg) REFERENCES TRUCK(CarReg)

( 1, DR1, 'SJG123', ADD_MONTHS(TRUNC(SYSDATE),0)-135 )
( 2, DR2, 'GBC222', ADD_MONTHS(TRUNC(SYSDATE),0)-135 )
( 3, DR1, 'GBC270', ADD_MONTHS(TRUNC(SYSDATE),0)-133 )
( 4, DR3, 'SJG123', ADD_MONTHS(TRUNC(SYSDATE),0)-130 )
( 5, DR22, 'SJG123', ADD_MONTHS(TRUNC(SYSDATE),0)-130 )
( 6, DR22, 'GBC222', ADD_MONTHS(TRUNC(SYSDATE),0)-124 )
( 7, DR7, 'KKK007', ADD_MONTHS(TRUNC(SYSDATE),0)-123 )
( 8, DR1, 'SJG123', ADD_MONTHS(TRUNC(SYSDATE),0)-123 )
( 9, DR2, 'QRT834', ADD_MONTHS(TRUNC(SYSDATE),0)-123 )
(10, DR22, 'GBC270', ADD_MONTHS(TRUNC(SYSDATE),0)-122 )

这是我可以走多远。不知道如何继续。我在互联网的帮助下成功实现了这一目标。请指教。

SELECT DRIVER.LicenseCardNo AS LICENSE_NO, COUNT(TRIP.TripNo) AS TOTAL_NO_TRIPS
FROM DRIVER LEFT OUTER JOIN TRIP ON DRIVER.LicenseCardNo = TRIP.LicenseCardNo
GROUP BY DRIVER.LicenseCardNo
ORDER BY DRIVER.LicenseCardNo;

此代码列出了每个驾驶员旅行的次数。

所以现在我需要找到执行次数最多的所有司机的许可证号码(LicenseCardNo)。

1 个答案:

答案 0 :(得分:2)

你几乎就在那里。这是一种方法,使用Oracle中的分析函数:

with q as (
    SELECT DRIVER.LicenseCardNo AS LICENSE_NO, COUNT(TRIP.TripNo) AS TOTAL_NO_TRIPS
    FROM DRIVER LEFT OUTER JOIN TRIP ON DRIVER.LicenseCardNo = TRIP.LicenseCardNo
    GROUP BY DRIVER.LicenseCardNo
)
select licenseCardNo
from (select q.*, rank() over (order by Total_No_Trips order by 1 desc) as ranking
      from q
     ) q1
where ranking = 1
ORDER BY LicenseCardNo;

实际上,我也意识到你的原始查询是不必要的复杂。由于您拥有许可证号,因此您无需将连接返回到DRIVER。您可以将其表达为:

select licenseCardNo
from (select q.*, rank() over (order by Total_No_Trips order by 1 desc) as ranking
      from (select LicenseCardNo, count(*) as Total_No_Trips
            from trips t
            group by LicenseCardNo
           ) q
     ) q1
where ranking = 1
ORDER BY LicenseCardNo;

另外,如果您只想在输出中看到最大数字,那么您可以这样做:

order by 2 desc

在原始查询中。这将按计数而不是许可证号码排序。

另一种(通常效率较低)的方法是使用group by / join方法:

with q as (
    select LicenseCardNo, count(*) as Total_No_Trips
    from trips t
    group by LicenseCardNo
)
select q.*
from q
where Total_No_Trips = (select max(Total_No_Trips) from q)