我有以下数据子集:
Ticker A | Ticker B | Value 1 | Value 2
AAU AAV -0.49 0.98
AAU AAWW -0.68 -0.34
AAU AAXJ -0.82 0.54
AAU AB -0.49 -0.98
AAV AAWW 0.74 -0.52
AAV AAXJ 0.69 0.36
AAV AB 0.27 -1.00
AAWW AAXJ 0.89 0.61
AAWW AB 0.62 0.54
AAXJ AB 0.54 -0.34
使用MySQL,我需要根据代码返回“值1”和“值2”中的前3个(最大值)。例如,我想找到3个最大的“值1”和“值2”,其中股票代码为“AAWW”(可以存在于Ticker A或Ticker B列中),但我希望看到其他股票代码相关联有了它,每个值。根据上面的数据和那个场景,我想要的记录集是:
Ticker | Value 1 | Ticker | Value 2
AAV 0.89 AAXJ 0.61
AAXJ 0.72 AB 0.54
AB 0.62 AAU -0.34
理想情况下,我想在没有存储过程的情况下执行此操作。这可能吗?
答案 0 :(得分:1)
试试这个(假设你没有ID列,否则用ID替换@rownum / rank):
SELECT T1.SUB_Ticker, T1.VALUE1, T2.SUB_Ticker, T2.VALUE2
FROM
(SELECT CASE WHEN TickerA = 'AAWW' THEN TickerA ELSE TickerB END Ticker,
CASE WHEN TickerA = 'AAWW' THEN TickerB ELSE TickerA END SUB_Ticker,
VALUE1,
@rownum:=@rownum+1 ‘rank’
FROM data_table d, (SELECT @rownum:=0) r
WHERE TickerA = 'AAWW' OR TickerB = 'AAWW'
ORDER BY VALUE1 DESC
LIMIT 3) T1
JOIN
(SELECT CASE WHEN TickerA = 'AAWW' THEN TickerA ELSE TickerB END Ticker,
CASE WHEN TickerA = 'AAWW' THEN TickerB ELSE TickerA END SUB_Ticker,
VALUE2,
@rownum:=@rownum+1 ‘rank’
FROM data_table d, (SELECT @rownum:=0) r
WHERE TickerA = 'AAWW' OR TickerB = 'AAWW'
ORDER BY VALUE2 DESC
LIMIT 3) T2 ON T1.rank = T2.rank