条件后的条件

问题描述 投票:0回答:1

我必须打印条件为[a-g]的公司名称的最小值

select 'cheapest' ogolne,p.UnitPrice, p.productname,p.CategoryID, s.COMPANYNAME 
from products p inner join
suppliers s on s.supplierid = p.supplierid
where SUBSTRING(s.companyname,1,1)>='A' and SUBSTRING(s.companyname,1,1)<='G' and
unitprice in (select min(unitprice) from products where
unitprice is not null and unitprice<>0) 

但是有了这个,我找到了所有的最小值,但是我需要从[a-g]中得到最小值

cheapest    18,00   Chai    NULL    Exotic Liquids
cheapest    19,00   Chang   1   Exotic Liquids
cheapest    10,00   Aniseed Syrup   2   Exotic Liquids
cheapest    25,00   Grandma's Boysenberry Spread    2   Grandma Kelly's Homestead
cheapest    30,00   Uncle Bob's Organic Dried Pears 7   Grandma Kelly's Homestead
cheapest    14,00   Sasquatch Ale   1   Bigfoot Breweries
cheapest    18,00   Steeleye Stout  1   Bigfoot Breweries
cheapest    263,50  Côte de Blaye   1   Aux joyeux ecclésiastiques
cheapest    18,00   Chartreuse verte    1   Aux joyeux ecclésiastiques
cheapest    53,00   Manjimup Dried Apples   7   G'day, Mate
cheapest    7,00    Filo Mix    5   G'day, Mate
sql sql-server min
1个回答
0
投票

您可以使用SUBSTRING分组(s.companyname,1,1)并加入一个元组(如果您的数据库承认元组)

    select 'cheapest' ogolne
        ,p.UnitPrice
        , p.productname
        ,p.CategoryID
        , s.COMPANYNAME 
    from products p inner join
    suppliers s on s.supplierid = p.supplierid
    where SUBSTRING(s.companyname,1,1)>='A' 
    and SUBSTRING(s.companyname,1,1)<='G'
     and
    ( SUBSTRING(s.companyname,1,1) ,  unitprice)   in ( 
      select SUBSTRING(s.companyname,1,1),  min(unitprice) 
        from products where
        unitprice is not null and unitprice<>0 
        GRUP BY SUBSTRING(s.companyname,1,1)
    ) 

或加入子查询

    select 'cheapest' ogolne
        ,p.UnitPrice
        , p.productname
        ,p.CategoryID
        , s.COMPANYNAME 
    from products p 
    INNER JOIN  (
        SUBSTRING(s.companyname,1,1)) unitprice,  in ( select SUBSTRING(s.companyname,1,1) comp,  min(unitprice) 
        from products where
        unitprice is not null and unitprice<>0 
        GRUP BY SUBSTRING(s.companyname,1,1)
    ) t on  SUBSTRING(s.companyname,1,1))  = t.comp and p.unitPrice =  t.min_price
    suppliers s on s.supplierid = p.supplierid
    where SUBSTRING(s.companyname,1,1)>='A' 
    and SUBSTRING(s.companyname,1,1)<='G'
     and SUBSTRING(s.companyname,1,1)
© www.soinside.com 2019 - 2024. All rights reserved.