查找平均最小值并选择所有值

时间:2019-09-18 15:22:33

标签: sql sql-server

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

(123, 123) (345, 123)  are connected.
(123, 123) (345, 345)  are NOT connected.
(345, 123) (345, 345)  are NOT connected.

公司有多种不同的产品

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

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

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

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

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

1 个答案:

答案 0 :(得分:0)

我将使用条件聚合:

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”分配给具有最低价格的产品。如果有关系,则可以任意选择一个。