3

(请参阅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 名,我需要按 升序对前 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 名公司需要从最低到最高协议进行排序。最好用一个查询。你知道如何?

4

1 回答 1

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

于 2012-09-02T11:53:07.307 回答