-3

我的 SQL 技能低下存在问题。在Products具有结构Id, Supplier, Brand,的表中Article,我必须按andPrice对所有记录进行分组,并选择在查询ID 中指定的组中没有最低价格或价格低于其他价格超过 5% 的组。BrandArticleSupplier

尝试使用GROUP BYand HAVING,但没有任何效果。有任何想法吗?

算法:
1. 将所有记录按BrandArticle
2. 仅选择包含指定之一的Supplier
组 3. 如果在选定的组中指定Supplier的最低Price或他的Price最低比另一个最低的不超过 5%,则选择该组

4

2 回答 2

1

我将问题解释为查找给定供应商的所有产品,其中供应商的价格比最低价格高出 5% 以上。这种语言有点难以理解,所以这是我最好的猜测。

如果是这样,请使用窗口函数来计算组的最低价格,然后使用简单的逻辑:

select p.*
from (select p.*,
             min(price) over (partition by supplier, article) as MinPrice
      from products p
     ) p
where SupplierID = @SupplierId and
      price > 1.05 * MinPrice;

编辑:

要获得min()排除某些供应商:

select p.*
from (select p.*,
             min(case when supplier not in (<list>) then price end) over
                  (partition by supplier, article) as MinPrice
      from products p
     ) p
where SupplierID = @SupplierId and
      price > 1.05 * MinPrice;
于 2013-07-07T19:19:04.230 回答
0

不完全确定你在追求什么,但如果我没看错你的问题,怎么样

Select * From Products p
Where price != (Select Min(Price)
               From products
               Where Brand = p.Brand
                 And Article = p.Article)
  And price < 0.95 *
              (Select Min(Price)
               From products
               Where id != p.Id
                  And Brand = p.Brand
                  And Article = p.Article)

如果这不是您想要的,它仍然应该为您提供有关如何为您想要的内容编写正确 sql 的线索......

于 2013-07-07T18:15:05.160 回答