从GROUP BY获取最上一行

时间:2016-08-08 22:54:47

标签: mysql sql

离开我的上一个问题:Complex Grouping in SQL Query ...

在每个分组中,我只想抓住具有最高'step'值的行。

这是我们在上一个问题中提出的问题:

SELECT a.*, b.*
FROM (
    SELECT request_id
    FROM tableA
    GROUP BY request_id
    HAVING MAX(page_views) <= 0 AND MAX(step) <= 2
) AS sumQ
INNER JOIN tableA AS a ON sumQ.request_id = a.request_id
INNER JOIN tableB AS b ON a.request_id = b.id

返回:

id   request_id   page_views   step   name          phone
----------------------------------------------------------------
 8   3            0            0      Jacob Clark   434-343-434
 9   3            0            1      Jacob Clark   434-343-434
10   4            0            0      Alex Smith    222-112-2112
11   4            0            1      Alex Smith    222-112-2112
12   4            0            2      Alex Smith    222-112-2112

这是我想要的,但是,我意识到在每个组中(group by request_id)我只需要具有最高'step'值的行。如何修改现有查询以仅返回:

id   request_id   page_views   step   name          phone
----------------------------------------------------------------
 9   3            0            1      Jacob Clark   434-343-434
12   4            0            2      Alex Smith    222-112-2112

2 个答案:

答案 0 :(得分:0)

然后在逻辑中包含step

SELECT a.*, b.*
FROM (SELECT request_id, MAX(step) as maxstep
      FROM tableA
      GROUP BY request_id
      HAVING MAX(page_views) <= 0 AND MAX(step) <= 2
     ) sumQ INNER JOIN
     tableA a
     ON sumQ.request_id = a.request_id AND
        sumQ.maxstep = a.step INNER JOIN
     tableB b
     ON a.request_id = b.id;

答案 1 :(得分:-1)

您是否尝试在ORDER BY字段设置step,然后获取TOP记录?

SELECT a.*, b.*
FROM (
    SELECT TOP 1 request_id
        FROM tableA
        GROUP BY request_id
        HAVING MAX(page_views) <= 0 AND MAX(step) <= 2
        ORDER BY step DESC
) AS sumQ
INNER JOIN tableA AS a ON sumQ.request_id = a.request_id
INNER JOIN tableB AS b ON a.request_id = b.id