基于col2分组值的col1捕获值

时间:2019-06-27 16:16:01

标签: mysql sql

这是我表的一般结构

USERID | QUANTITY | FRIEND_ID |         DATE
---------------------------------------------------
     1 |        3 |         7 | 2019-06-22 10:00:00
     2 |        2 |         8 | 2019-06-22 11:00:00
     1 |        2 |         5 | 2019-06-22 12:00:00

然后我要像这样将这些数据分组

SELECT USERID,
       SUM(QUANTITY) AS COUNT,
       // I NEED THE FRIEND_ID OF THE RECORD WITH MAX(DATE)
       MAX(DATE)
FROM THISTABLE
GROUP BY USERID

如何根据另一列的分组值选择一列的值?

1 个答案:

答案 0 :(得分:0)

您可以将查询加入表中以获得FRIEND_ID:

SELECT g.USERID, g.COUNT, t.FRIEND_ID, g.MAXDATE
FROM (
  SELECT USERID, SUM(QUANTITY) AS COUNT, MAX(DATE) AS MAXDATE
  FROM THISTABLE
  GROUP BY USERID
) g INNER JOIN THISTABLE t
on t.USERID = g.USERID AND t.DATE = g.MAXDATE