【问题标题】:Find average minimum and select all values查找平均最小值并选择所有值
【发布时间】:2019-09-18 23:37:22
【问题描述】:

我有一张包含公司、产品、地区和价格的表格

Company | Product | Region | Price
ABC          ROO      1       10
ABC          BAR      1       12 
ABC          BAR      2       12
DEF          DOO      1       11
DEF          BAR      2       8 
etc....

有多种不同的产品与公司相关联

我有以下代码可以找到每个公司每个地区最便宜的产品并对其进行调整

WITH tableFix
 AS
(
SELECT *
FROM (
SELECT *,
    ROW_NUMBER() OVER (PARTITION BY T.Company, T.Region ORDER BY T.Price) AS RegionalPosition 

FROM dbo.MainTablePlus AS T
) AS B   
WHERE B.SupplierRegionalTariffPosition =1 -- Filters applied here - is currently set to retrieve top 1 tariffs per region
)
SELECT Company ,Product, [Region 1],[Region 2],[Region 3],[Region 4],[Region 4] 
FROM 
(
SELECT Company, Product, Region, Price
FROM tableFix) UP
PIVOT (MIN(Price) FOR Region IN ([Region 1],[Region 2],[Region 3],[Region 4],[Region 4] )) AS pvt
ORDER BY Company, Product

但是,当我运行它时,当一个地区有更便宜的产品时,它会为每家公司挑选一种以上的产品,如下所示:

Company | Product | Region 1 | Region 2 | Region 3.....
 ABC        ROO        NA         12        10
 ABC        FAR        6          NA        NA
 DEF        BAR        9          8         7
 GHI        FOO        8          6         9

它为 ABC 公司挑选了两种产品,但我希望它像这样挑选最便宜的整体产品

Company | Product | Region 1 | Region 2 ...... Region 10
 ABC        ROO        10         12
 DEF        BAR        9          8
 GHI        FOO        8          6

我在 Microsoft SQL Server Management Studio 上执行此操作

【问题讨论】:

  • 当同一家公司不同地区的不同产品可能最便宜时,您如何决定选择哪种产品?
  • 我想要总体上最便宜的产品,然后在所有地区展示该产品
  • 总体上定义最便宜的产品。对我来说听起来应该只有一个,但你的样品展示了很多产品。按公司或按地区或两者的组合是最便宜的产品。解释逻辑,我们可以提供帮助。
  • 公司 ABC 有两个不同的区域。您在 partition by 子句中包含区域,因此您将从 CTE 中获得公司 ABC 的两行。
  • @JuanCarlosOropeza 一家公司有很多产品,但我想在尽可能多的地区选择总体上最便宜的产品。

标签: sql sql-server


【解决方案1】:

我会使用条件聚合:

select company,
       min(case when region = 'Region 1' then price end) as region_1,
       min(case when region = 'Region 2' then price end) as region_2,
       min(case when region = 'Region 3' then price end) as region_3,
       . . .
from (select mtp.*,
             min(seqnum) over (partition by company, product) as product_price_seqnum
      from (select mtp.*,
                   row_number() over (partition by company order by price) as price_seqnum
            from MainTablePlus mtp
           ) mtp
     ) mtp
where product_price_seqnum = 1
group by company;

两个级别的子查询将值“1”分配给具有最低价格的产品。如果有关系,则任意选择一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 2022-10-26
    相关资源
    最近更新 更多