0

假设我有一张名为 COFFEE 的表格,其中显示了公交车站和公交车站 10 个街区内的所有咖啡店:

    BusStationID| CoffeeShopID |  Distance (in city blocks)
    1|2103|2
    1|2222|2
    1|8864|7
    1|9920|5
    1|3544|2
    1|4830|2
    1|4823|6
    1|9561|2
    7|6262|2
    7|8561|10
    7|9510|5
    7|2744|1       
    7|4223|9
    7|5960|3

[编辑:明确问题是如何通过非程序查询来做到这一点]

而且我必须编写一个查询(而不是 proc)来显示每个公交车站到最近的五家咖啡店的平均距离。

我可以找到特定巴士站的前 5 家最近的咖啡店:

           select avg(top5.distance) as AvgDistToFiveClosest
           from
           (
           select top 5 distance from COFFEE where busstationid = 1
           order by distance
           ) as top5

但是如何将其连接为子查询并使 AvgDistToFiveClosest 成为我的主查询中返回的列:

        select BusStationId,  AvgDistToFiveClosest
        from COFFEE...
         ??????

鉴于上面的示例数据,查询应返回:

     BusStationID | AvgDistToFiveClosest
           1 | 2
           7 | 4
4

3 回答 3

2

这是 Oracle (9g+) SQL 代码,已更正,我找到了单个选择语句的答案

with
distanceRanks as
(
  SELECT
    busstationid,
    distance,
    --rank the rows on the distance column from smallest to longest, and differentiate equal distances by rownum
    rank() over ( partition by busstationid
                  order by distance, rownum asc) as ranking
  FROM coffee
  ORDER BY 1 asc
)
SELECT busstationid, avg(distance)
FROM distanceRanks
WHERE ranking < 6
group by busstationid;
于 2012-08-06T18:46:10.333 回答
1

尝试这个:

SELECT c.BusStationID, AVG(c.distance)
FROM COFFEE c
WHERE c.CoffeeShopID IN 
(SELECT TOP 5 c2.CoffeeShopID FROM COFFEE c2 WHERE c2.BusStationID = c.BusStationID
ORDER BY c2.distance)
GROUP BY c.BusStationID
于 2012-08-06T21:12:38.980 回答
0

尝试这个

Select distinct busstationid , (select top 5 avg(distance) from coffee ce where ce.busstationid = b.busstationid order by distance) as AvgDistToFiveClosest
From coffee b
于 2012-08-07T05:48:20.890 回答