在多连接中获取最大数据量

tf7tbtn2  于 2021-07-26  发布在  Java
关注(0)|答案(4)|浏览(289)

我有这样的数据
采购订单(po)

po_id   pi_id    store
112     789      ABC
113     101      DEF
114     102      GHI
115     103      JKL

采购项目(pi)

pi_id  barcode   price    date
789    123       500      2020-06-04
101    123       400      2020-06-03
102    456       500      2020-06-02
103    456       400      2020-06-01

产品

barcode   product
123       milk
456       tea

如果商店不包括“ghi”,我想知道每个条形码的最新价格
预期结果

barcode  price
123      500
456      400

我该怎么办?

x6h2sr28

x6h2sr281#

一个选项使用相关子查询:

select
    p.barcode,
    (
        select pi.price
        from purchase_items pi
        inner join purchase_orders po on po.pi_id = pi.pi_id
        where pi.barcode = p.barcode and po.store <> 'GHI'
        order by pi.date desc limit 1
    ) price
from product p
cetgtptt

cetgtptt2#

row_number() 有一种方法:

select pi.barcode, pi.price
from (select pi.*, row_number() over (partition by pi.barcode order by pi.date desc) as seqnum
      from purchase_items pi
      where not exists (select 1
                        from purchase_orders po 
                        where po.pi_id = pi.pi_id and po.store = 'GHI'
                       )
     ) pi
where seqnum = 1;
cigdeys3

cigdeys33#

使用join with max函数:

select pi.barcode, max(pi.price)
from purchase_items pi
  join purchase_order po on po.pi_id=pi.pi_id
where po.store!='GHI'
group by pi.barcode
tuwxkamq

tuwxkamq4#

使用子查询的一种方法。

SELECT 
    DISTINCT
    a.`barcode`,
    a.`price` 
FROM
    purchase_items a 
WHERE a.`date` = 
    (SELECT 
        MAX(`date`) 
    FROM
        purchase_items i 
    WHERE i.barcode = a.barcode 
        AND 'GHI' != 
        (SELECT 
            store 
        FROM
            purchase_order 
        WHERE pi_id = i.`pi_id` 
        LIMIT 1)) ;

相关问题