我有以下数据集
ID P C1 C2 XR
1 1 GBP USD 1.6
2 2 GBP USD 1.7
3 1 GBP EUR 0.84
4 2 GBP EUR 0.83
5 1 GBP CHF 1.8
6 2 GBP CHF 1.8
我试图获得每对的最小XR,因此结果应为
ID P C1 C2 XR
1 1 GBP USD 1.6
4 2 GBP EUR 0.83
5 1 GBP CHF 1.8
但是当我SELECT MIN(XR) GROUP BY C1,C2
时,如果启用了“ONLY_FULL_GROUP_BY”,我要么得不到正确的ID,要么收到警告说ID不在GROUP BY中
最近我得到的是:
SELECT t1.id, t1.C1, t1.C2, MIN(t2.XR) FROM xrates t1
LEFT JOIN xrates AS t2 ON t1.id = t2.id
GROUP BY t1.id, t1.C1, t1.C2
HAVING t1.C1 = 'GBP' AND t1.C2 IN ('USD','EUR')
答案 0 :(得分:2)
select rates.*
from xrates rates
where id in
(
select min(xrates.id) as minid
from xrates
inner join
(
select C1, C2, MIN(XR) as minxr
from xrates
GROUP BY C1, C2
HAVING C1 = 'GBP'
) x on x.c1 = xrates.c1 and x.c2 = xrates.c2 and x.minxr = xrates.xr
group by xrates.C1, xrates.C2
)
答案 1 :(得分:0)
SELECT x.*
FROM my_table x
JOIN
(SELECT grouping _id,MIN(ordering_id) min_ordering_id FROM my_table GROUP BY grouping_id) y
ON y.grouping_id = x.grouping_id
AND y.min_ordering_id = x.ordering_id;
(请注意,'grouping_id'可能会在多个列上形成!)
答案 2 :(得分:-1)
您不需要将表连接到自身,并且您不希望GROUP BY为id或每行都将是唯一的。以下内容应返回您指定的结果:
SELECT
xrates.id,
xrates.C1,
xrates.C2,
MIN(xrates.XR)
FROM xrates
WHERE xrates.C1 = 'GBP'
AND xrates.C2 IN ('USD','EUR')
GROUP BY
xrates.C1,
xrates.C2;