如何仅按用户计算第一个出现的组

时间:2017-11-28 23:40:27

标签: mysql

我有以下表结构:

CREATE TABLE `client_notes` (
`id` bigint(20) NOT NULL,
`client_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`note` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`datepost` datetime NOT NULL
) ENGINE=MyISAM

这里我存储了用户为客户插入的注释。 每个client_id都有一些注释,由user_id添加。目标是计算经纪人添加第一个注释的次数(额外选项可以是本周的期间,例如在where子句中)

+----+----------+-----------------------------+
| id | broker_id| client | datepost           |
+----+---------+------------------------------+
|  1 |    1     |   10   | 29-11-2017 10:00:00| <- this is first note for this client
|  2 |    2     |   10   | 29-11-2017 10:20:00|
|  3 |    2     |   15   | 28-11-2017 10:10:00| <- this is first note for this client
|  4 |    1     |   15   | 28-11-2017 10:20:00|
|  5 |    1     |   15   | 28-11-2017 10:30:00|
+----+----------+--------+--------------------+

输出应为:

+-----------+-------+
| broker_id | count |
+-----------+-------+
|     1     |   1   |
|     2     |   1   |
+-----------+-------+

1 个答案:

答案 0 :(得分:0)

首先,不要在简单的SQL标识符上使用不必要的和非标准的引号:

-- Note: example data column names don't match above table definition
select min(datepost) as datepost, client_id from ENGINE group by client_id

首先获得&#34;&#34;任何意味着订单和最低限度。您希望每个客户的日期最短:

select broker_id, count(*) as 'count'
from ENGINE as E
join (
    select min(datepost) as datepost, client_id from ENGINE group by client_id
) as A
on E.client_id = A.client_id
and E.datepost = A.datepost
group by broker_id

任何SELECT的结果都是一个表,可以操作,

raw_input()