[英]select minimum of one column maximum of another column
I have data as below: 我有如下数据:
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
I want to select rows for each SID where CID is minimum and Price is maximum. 我想为CID最小且价格最大的每个SID选择行。
Expected output: 预期产量:
PID SID CID Price
2 1 1 19
4 2 2 22
8 3 2 40
My query gives expected output. 我的查询给出了预期的输出。 But since I am new to MySQL, I am not sure if it is the optimum way of doing it. 但是由于我是MySQL的新手,所以我不确定这是否是最佳的实现方法。
Query: 查询:
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;
Edit #1: Sorry but I observed for set of data as below, the query does not return any output: 编辑#1:对不起,但我观察到如下数据集,查询未返回任何输出:
PID SID CID Price
11 6 1 18
12 6 1 19
13 6 2 30
However expected output is: 但是,预期输出为:
PID SID CID Price
11 6 1 19
As minimum CID for SID=6 is 1. And from values SID=6 and CID=1, maximum value of Price is 19. 由于SID = 6的最小CID为1,并且从值SID = 6和CID = 1,价格的最大值为19。
Any idea how to achieve it. 任何想法如何实现它。
Is this query optimum: 此查询是否最佳:
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
Surely you want 12, 6, 1, 19 !?!?!?!?!?!?! 您肯定要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 |
+-----+-----+-----+-------+
I think only one sub-query is enough to find the minimum CID
for each SID
and do the JOIN
s with sub-query to find the maximum Price
我认为只有一个子查询足以找到每个SID
的最小CID
,并使用子查询执行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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.