为每个组值mysql获取不同的ID

时间:2019-04-03 12:09:48

标签: mysql sql group-by distinct

我的结果集如下:

client_id   status
------------------
67          1
67          0
67          0
67          0
77          0

我只需要获取client_id条目为latest (top)的{​​{1}}。

我尝试关注,但都获得了067 and 77应该排除在外。

67

如何设置条件,以便我只能获取SELECT DISTINCT client_id FROM ( SELECT client_id, status FROM client_history WHERE (DATE(updated_on) BETWEEN '$from' AND '$to') ORDER BY DATE(updated_on) DESC ) as ch WHERE status = 0 GROUP BY client_id 为0的那些记录?

3 个答案:

答案 0 :(得分:1)

使用不存在的相关子查询

select distinct client_id
from lient_history a
where not exists (select 1 from lient_history b where a.client_id=b.client_id 
  and status=1) 
and (DATE(updated_on) BETWEEN '$from' AND '$to')

答案 1 :(得分:1)

要获取最新条目,可以使用相关子查询:

select ch.*
from client_history ch
where ch.updated_on = (select max(ch2.updated_on)
                       from client_history ch2
                       where ch2.client_id = ch.client_id and
                             date(updated_on) between ? and ?
                      );

请注意,它使用参数占位符(?)而不是字符串替换来传递值。

为此,您只需添加:

and status = 0

进行所需的过滤。

答案 2 :(得分:0)

请尝试以下一项,我认为它将解决您的问题。

Declare @FromDate Date, @ToDate Date
Set @FromDate = -- whatever date range you wanted to give
Set @ToDate =  -- whatever date range you wanted to give
SELECT DISTINCT client_id FROM dbo.Client_history 
WHERE cast(updated_on as DATE)>=@FromDate and cast(updated_on as DATE)<=@ToDate
AND status = 0
ORDER BY DATE(updated_on) DESC