选择最少一列另一列的最大值

时间:2018-03-16 15:01:40

标签: mysql sql max min

我的数据如下:

PID SID CID Price
1   1   1   18
2   1   1   19
3   1   2   10
4   2   2   22
5   2   2   21.35
6   3   2   25
7   3   7   30
8   3   2   40

我想为CID最小且价格最高的每个SID选择行。

预期产出:

PID SID CID Price
2   1   1   19
4   2   2   22
8   3   2   40

我的查询给出了预期的输出。但由于我是MySQL的新手,我不确定这是否是最佳方式。

查询:

select a.PID, a.SID, a.CID, a.Price
from Products a
inner join (select SID as SID, min(CID) as CID_Min, max(Price) as Price_Max
            from Products
            group by SID) b
on a.SID=b.SID and
   a.CID=b.CID_Min and
   a.Price=b.Price_Max;

编辑#1: 抱歉,但我观察了如下数据集,查询不会返回任何输出:

PID SID CID Price
11  6   1   18
12  6   1   19
13  6   2   30

但预期输出为:

PID SID CID Price
11  6   1   19

SID = 6的最小CID为1.并且从值SID = 6和CID = 1开始,价格的最大值为19.

知道如何实现它。

此查询是否最佳:

select t.SID, t.CID, t.Price
from Products t
inner join
  (select p.SID as SID_max, p.CID as CID_max, max(p.Price) as Price_max
   from Products p
   inner join 
     (select SID as SID_min, min(CID) as CID_min
      from Products
      group by SID) p_min
   on p.SID=p_min.SID_min and
      p.CID=p_min.CID_min
   group by p.SID, p.CID
  ) p_max
on t.SID=p_max.SID_max and
   t.CID=p_max.CID_max and
   t.Price=p_max.Price_max

2 个答案:

答案 0 :(得分:0)

当然你想要12,6,1,19!?!?!?!?!?!?!

SELECT a.* 
  FROM my_table a 
  JOIN 
     ( SELECT x.sid
            , x.cid
            , MAX(price) price 
         FROM my_table x 
         JOIN 
            ( SELECT sid
                   , MIN(cid) cid 
                FROM my_table 
               GROUP 
                  BY sid
            ) y 
           ON y.sid = x.sid 
          AND y.cid = x.cid 
        GROUP 
           BY sid
            , cid
     ) b 
    ON b.sid = a.sid 
   AND b.cid = a.cid 
   AND b.price = a.price;
+-----+-----+-----+-------+
| pid | sid | cid | price |
+-----+-----+-----+-------+
|  12 |   6 |   1 |    19 |
+-----+-----+-----+-------+

答案 1 :(得分:0)

我认为只有一个子查询足以找到每个CID的最小SID,并使用子进行JOIN查询以查找最大Price

SELECT p.* FROM Products p
INNER JOIN (
   SELECT sid, min(cid) cid from Products
   GROUP BY sid
) pr ON pr.sid = p.sid AND
p.price = (SELECT MAX(price) FROM Products WHERE sid = pr.sid AND cid = pr.cid)