1

我有以下数据集

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')
4

3 回答 3

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
)

SQLFiddle 演示

于 2013-11-13T08:28:48.050 回答
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' 可能在不止一列上形成!)

于 2013-11-13T08:33:21.107 回答
-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;
于 2013-11-13T08:33:00.323 回答