分组最大值

Tom*_*now 9 mysql sql

我有一张表,我试图检索每个安全的最新位置:

桌子:

我创建表的查询: SELECT id, security, buy_date FROM positions WHERE client_id = 4

+-------+----------+------------+
| id    | security | buy_date   |
+-------+----------+------------+
|    26 | PCS      | 2012-02-08 |
|    27 | PCS      | 2013-01-19 |
|    28 | RDN      | 2012-04-17 |
|    29 | RDN      | 2012-05-19 |
|    30 | RDN      | 2012-08-18 |
|    31 | RDN      | 2012-09-19 |
|    32 | HK       | 2012-09-25 |
|    33 | HK       | 2012-11-13 |
|    34 | HK       | 2013-01-19 |
|    35 | SGI      | 2013-01-17 |
|    36 | SGI      | 2013-02-16 |
| 18084 | KERX     | 2013-02-20 |
| 18249 | KERX     | 0000-00-00 |
+-------+----------+------------+
Run Code Online (Sandbox Code Playgroud)

我一直在搞乱基于这个页面的查询版本,但我似乎无法得到我正在寻找的结果.

这是我一直在尝试的:

SELECT t1.id, t1.security, t1.buy_date 
FROM positions t1
WHERE buy_date = (SELECT MAX(t2.buy_date)
                    FROM positions t2
                    WHERE t1.security = t2.security)
Run Code Online (Sandbox Code Playgroud)

但这只会让我回报:

+-------+----------+------------+
| id    | security | buy_date   |
+-------+----------+------------+
|    27 | PCS      | 2013-01-19 |
+-------+----------+------------+
Run Code Online (Sandbox Code Playgroud)

我正在尝试获取每个证券的最大/最新购买日期,因此每个证券的结果将有一行,最近的购买日期.任何帮助是极大的赞赏.

编辑:必须以最大购买日期返回头寸的ID.

Vis*_*kia 18

您可以使用此查询.您可以将时间缩短75%.我检查了更多的数据集.子查询需要更多时间.

SELECT p1.id, 
       p1.security, 
       p1.buy_date 
       FROM positions p1
left join
            positions p2
                on p1.security = p2.security
                   and p1.buy_date < p2.buy_date
      where 
      p2.id is null;
Run Code Online (Sandbox Code Playgroud)

SQL-Fiddle 链接


Tar*_*ryn 9

您可以使用子查询来获取结果:

SELECT p1.id, 
  p1.security, 
  p1.buy_date 
FROM positions p1
inner join
(
  SELECT MAX(buy_date) MaxDate, security
  FROM positions 
  group by security
) p2
  on p1.buy_date = p2.MaxDate
  and p1.security = p2.security
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo

或者您可以在WHERE子句中使用以下内容:

SELECT t1.id, t1.security, t1.buy_date 
FROM positions t1
WHERE buy_date = (SELECT MAX(t2.buy_date)
                  FROM positions t2
                  WHERE t1.security = t2.security
                  group by t2.security)
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo


Hog*_*gan 5

这是通过一个简单的组来完成的.您希望按证券分组并获得buy_date的最大值.SQL:

SELECT security, max(buy_date) 
from positions
group by security
Run Code Online (Sandbox Code Playgroud)

请注意,这比bluefeet的答案快,但不显示ID.