如何按列A首先排序,返回前3位,然后在一个查询中按列B排序结果?

时间:2012-09-02 11:16:01

标签: mysql

(有关此帖子的工作示例,请参阅SQLFiddle

我有一张包含股票信息的表格,如下所示:

sp100_id  _date         bullishness  agreement
----------------------------------------------
1         2011-03-16    1.01          0.33
1         2011-03-17    0.85          1.28
1         2011-03-18    0.89          1.25
1         2011-03-21    1.46          1.21
1         2011-03-22    0.39          2.53
2         2011-03-16    3.07          1.27
2         2011-03-17    2.09          0.80
2         2011-03-18    0.91          0.12
2         2011-03-21    1.50          0.00
2         2011-03-22    2.62          1.10
3         2011-03-16    0.73          1.13
3         2011-03-17    1.13          1.21
3         2011-03-18    1.12          0.45
3         2011-03-21    1.00          1.01
3         2011-03-22    1.00          0.53
4         2011-03-16    0.40          1.10
4         2011-03-17    2.40          0.03
4         2011-03-18    3.16          0.10
4         2011-03-21    0.86          0.50
4         2011-03-22    1.00          0.10

我需要将公司(sp100_id)按照他们的平均bullishness的顺序排在前3位:

SELECT 
  sp100_id, 
  AVG(bullishness) as bullishness, 
  AVG(agreement) AS agreement 
FROM stocks 
WHERE _date BETWEEN '2011-03-16' AND '2011-03-22' 
GROUP BY sp100_id LIMIT 3

这样可以正常工作,结果是

SP100_ID    BULLISHNESS AGREEMENT
2           2.038           0.658
4           1.564           0.366
3           0.996           0.866

现在我有前3名,我需要按AGREEMENT重新排序前三名,升序:

SP100_ID    BULLISHNESS AGREEMENT
4           1.564           0.366
2           2.038           0.658
3           0.996           0.866

这可以用一个查询吗?我试过以下但是没有用。它仍然只按bullishness

排序
SELECT 
  sp100_id, 
  AVG(bullishness) as bullishness, 
  AVG(agreement) AS agreement 
FROM stocks 
WHERE _date BETWEEN '2011-03-16' AND '2011-03-22' 
GROUP BY sp100_id 
ORDER BY bullishness DESC, agreement ASC LIMIT 3

所以要明确:(1)我需要找到具有最高平均牛市的前3家公司(2)这个前3名需要从最低到最高协议订购。最好有一个查询。你知道吗?

1 个答案:

答案 0 :(得分:3)

它被称为结构化查询语言,因为您可以构建查询(即虚拟表)嵌套在其他查询中的结构。

接受你的第一个查询,这是正确的,除了它需要自己的ORDER BY子句,然后将它嵌套在另一个查询中,就像这样。

SELECT * 
  FROM (
           SELECT sp100_id,  
                  AVG(bullishness) as bullishness, 
                  AVG(agreement) AS agreement 
             FROM stocks 
            WHERE _date BETWEEN '2011-03-16' AND '2011-03-22' 
         GROUP BY sp100_id
         ORDER BY bullishness DESC
            LIMIT 3
  ) subquery
  ORDER BY agreement ASC

小提琴:http://sqlfiddle.com/#!2/c9ff0/7/0