从不同表获取列的SQL查询

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

我有 2 个表,

Product
Prices
,我想为
Product
表中的每个 ID 获取表
ID_Forn
中的
min(Price)
Prices

 Product                      Prices

| ID | Desc   |      | ID | ID_Forn | PRICE |
| -- | ------ |      | 1  | 101     | 10€   |
| 1  | Prod 1 |      | 1  | 102     | 11€   | 
| 2  | Prod 2 |      | 1  | 103     | 13€   |
| 3  | Prod 3 |      | 2  | 101     | 9€    |
| 4  | Prod 4 |      | 2  | 102     | 8€    |

通过此查询

SELECT 
    P.ID, 
    Price = (SELECT MIN(Price) 
             FROM Prices PP (NOLOCK) 
             WHERE P.ID = PP.ID)
FROM 
    Product P(NOLOCK)

我只能得到

ID
MIN(Price)
,永远无法得到
ID_Forn

有人可以帮助我吗?

sql sql-server
2个回答
0
投票

我怀疑以下内容会给您带来您想要的结果;在这里,对于每个相关的产品行,子查询应用以返回两列。

根据您的数据,您可能希望以特定方式处理重复项,例如

with ties

select p.Id, p.desc. pr.*
from Product p
outer apply (
  select top(1) Id_forn, Price
  from Prices pr
  where pr.Id = p.Id
  order by PRICE 
)pr;

0
投票

这个 sql 可以比我在这里展示的更简洁,但我希望它可以让您轻松了解这些连接如何工作的逻辑:

select
    products.ID,
    prices.id_forn,
    prices.price
from
    Products products
    inner join
    (
        select 
            id, id_forn, price
        from
        (
        select 
            id,
            id_forn,
            price,
            row_number() over (partition by id order by price) as seq,
            from Prices
        ) A
        where A.seq = 1
    ) prices
    on products.ID = prices.id
    
© www.soinside.com 2019 - 2024. All rights reserved.