简体   繁体   English

按组的SQL值与最大列值的比率

[英]SQL ratio of value to max column value by group

I thought this would be of general interest to the group because it is an actual job interview SQL question that I got wrong. 我认为这对于小组来说是普遍感兴趣的,因为这是我错了的一个实际的面试SQL问题。 I think I was close but can someone provide the correct answer? 我想我很亲密,但有人可以提供正确答案吗?

Brand  |  Model  |  Price
Braun  |  KF7150 |  98
Braun  |  KF7000 |  70
Braun  |  KF400  |  55
Krups  |  KM730  |  67
Krups  |  KM4689 |  130
Krups  |  EC311  |  50

For the above table (Coffee), provide the code that displays brand, model, price, and the ratio of each model's price to the highest price of its brand, rounded to nearest 2 decimal places. 对于上表(咖啡),提供显示品牌,型号,价格以及每种型号价格与其品牌最高价格的比率的代码,四舍五入到小数点后两位。

This code I know is wrong because it simply selects the overall max price (130). 我知道的这段代码是错误的,因为它只是选择总体最高价格(130)。

SELECT Brand, Model, Price, ROUND(Price/(SELECT MAX(Price) FROM Coffee),2)
 as Price_to_Brand_Highest
FROM Coffee
ORDER BY Brand;

I tried a self join but all the ratios came back as 1 because each price was divided by itself. 我尝试了自我加入,但所有比率均返回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;

You didn't specify a DBMS, so this is ANSI standard SQL: 您没有指定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;

Online example: http://rextester.com/HFZZRP41164 在线示例: http : //rextester.com/HFZZRP41164

Before window functions were added to standard SQL, one method would be to join on a subquery that calculates the max value. 在将窗口函数添加到标准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;
; 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM