我认为这对小组来说是普遍感兴趣的,因为这是一个实际的求职面试SQL问题,我错了。我想我很接近,但有人可以提供正确答案吗?
Brand | Model | Price
Braun | KF7150 | 98
Braun | KF7000 | 70
Braun | KF400 | 55
Krups | KM730 | 67
Krups | KM4689 | 130
Krups | EC311 | 50
对于上表(咖啡),请提供显示品牌,型号,价格以及每个型号价格与其品牌最高价格的比率的代码,四舍五入到最接近的2位小数。
我知道这段代码是错误的,因为它只选择整体最高价格(130)。
SELECT Brand, Model, Price, ROUND(Price/(SELECT MAX(Price) FROM Coffee),2)
as Price_to_Brand_Highest
FROM Coffee
ORDER BY Brand;
我尝试了自我加入,但所有比率都回归为1,因为每个价格都是自己分开的。
SELECT C1.Brand, C1.Model, C1.Price, ROUND(C1.Price/(SELECT MAX(C2.Price)
FROM Coffee where C1.Brand=C2.Brand),2) as Price_to_Brand_Highest
FROM Coffee C1
JOIN Coffee C2 on C1.Model=C2.Model
GROUP BY C1.Model
ORDER BY C1.Brand;
答案 0 :(得分:4)
您没有指定DBMS,因此这是ANSI标准SQL:
select brand, model, price,
round(price / max(price) over (partition by brand), 2) as price_ratio
from coffee
order by brand, model;
答案 1 :(得分:2)
在将窗口函数添加到标准SQL之前,一种方法是连接一个计算最大值的子查询。
SELECT
C1.*,
ROUND(C1.Price/C2.MaxBrandPrice, 2) as Price_to_Brand_Highest
FROM Coffee C1
JOIN (
Select Brand, max(Price) as MaxBrandPrice
From Coffee
Group by Brand
) C2
on (C1.Brand = C2.Brand)
ORDER BY C1.Brand, C1.Model;
答案 2 :(得分:0)
; with Max_v as (
Select Brand, max(Price) as MaxBrandPrice
From Coffee
Group by Brand
)
select Coffee.*, Max_v.price/(Max_ps.MaxBrandPrice*1.0)
from Coffee, Max_v
where D.Disease_ID = Max_ps.Disease_ID
order by D.Disease_ID, D.ps desc