为每个(汽车,型号)选择最大'租赁价格'

时间:2018-04-26 14:49:02

标签: sql oracle

我去了两张桌子;

表A:

 @Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.draw();

}

表B:

+--------+-----------+-------------+
| rentID | carNumber | rentalPrice |
+--------+-----------+-------------+
| Q16    | 2255DFS   |        1150 |
| Q14    | 1104RDC   |         250 |
| Q02    | 1475MHG   |         447 |
| Q11    | 8552FCG   |         214 |
+--------+-----------+-------------+

我需要为每个汽车品牌和型号,rentID,汽车品牌和汽车模型获得最大租金价格。

使用给定的表,我想得到的输出是:

  1. Q16 AUDI A3 1150
  2. Q02 VOLKSWAGEN PASSAT 447
  3. 到目前为止,我得到了这个:

    +---------+------------+--------+
    | number  |   brand    | model  |
    +---------+------------+--------+
    | 2255FDS | AUDI       | A3     |
    | 1104RDC | AUDI       | A4     |
    | 1475MHG | VOLKSWAGEN | PASSAT |
    | 8552FCG | VOLKSWAGEN | POLO   |
    +---------+------------+--------+
    

    但如果我尝试选择rentID,我只需获得表中的所有租金。

3 个答案:

答案 0 :(得分:0)

您可以使用分析函数:

SELECT rc.*
FROM (SELECT c.brand, c.model, r.*,
             MAX(r.rentalPrice) OVER (PARTITION BY c.brand, c.model) as max_rp
      FROM RENTAL_DETAILS r INNER JOIN
           CAR c
           ON c.number = r.carNumber
     ) rc
WHERE rentalPrice = max_rp;

答案 1 :(得分:0)

您是否可以使用子查询首先查找最高租金价格,然后使用此结果来驱动查询感兴趣的列?

select r.rentalPrice, c.brand, c.model, r.rentID
from cars c 
join rentals r on c.carNumber = r.number
where r.rentalPrice in (
  select max(r.rentalPrice) 
  from rentals r
  join cars c on r.number = c.carNumber 
  group by c.brand, c.model);

如果您以相同的最高价格租用> 1,则可能无法提供正确的结果。

答案 2 :(得分:0)

SELECT 
    * 
FROM 
(SELECT 
    Brand 
    ,carNumber 
    ,rentalprice
    ,RANK() OVER (PARTITION BY brand ORDER BY rentalprice DESC) AS highest 
FROM 
    dbo.Table_A
JOIN dbo.Table_B ON Number=carNumber) filterdtable
WHERE filterdtable.highest = 1

使用派生表过滤结果。希望这可以帮助!