繁体   English   中英

从具有最低价格的表中获取所有数据

[英]Get all data from table who has minimum price

我的表 t1 中有以下数据

unique_id   myid  price1   price2  price3  price4
1           100    20       30      40      50
2           200    12       24      48      90
3           100    15       20      30      25
4           300    100      200     300     400
5           400    10       10      20      40
6           100    5        6       7       8
7           200    1        2       3       4

现在我想要特定myid的数据,其price3最低

预期 output:

unique_id   myid  price1   price2  price3  price4
1           100    5        6       7       8
2           200    1        2       3       4
4           300    100      200     300     400

我试过以下查询:

select t1.*,t2.txn_amount from table1 t1
left join table1 t2 on t2.ummyid = t1.myid
where t1.myid IN (100,200,300) 
GROUP by t1.myid HAVING min(price3)

但它没有按预期工作。

如果您使用的是 MySQL 8.0,则以下解决方案应使用 window function row_number工作。 这是演示

select
  unique_id,   
  myid,  
  price1,  
  price2,  
  price3,  
  price4
from
(
  select
    unique_id,   
    myid,  
    price1,  
    price2,  
    price3,  
    price4,
    row_number() over (partition by myid order by price3) as rn
  from myTable
) subq
where rn = 1

您必须使用分析函数,请使用以下查询

    select unique_id,   myid,  price1,   price2,  price3,  price4 from
(slect unique_id,   myid,  price1,   price2,  price3,  price4, 
row_number() over(partition by myid order by price3) as rnk from table) qry
where rnk = 1;

如果您的数据库版本不允许超过分区`,您可以使用与子查询的连接来获取最小值

select * from table1 t1
inner join  (
    select  myid, min(price3) min_price
    from table1 
    group by myid

    )  t on t.myid = t1.myid
             and t.min_price = t1.price

对于你的情况

    select t1.*
    , t2.txn_amount 

    from table1 t1
    inner join  (
        select  myid, min(price3) min_price
        from table1 
        group by myid

        )  t on t.myid = t1.myid
                 and t.min_price = t1.price
    left join table1 t2 on t2.ummyid = t1.myid
    where t1.myid IN (100,200,300) 
    GROUP by t1.myid 

我认为这个解决方案应该有效:

Select distinct  myid,
  min(price3)
from t1 group by myid

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM