为每个组值获取不同的 ID mysql
Get distinct ids for each group value mysql
我有一个结果集如下:
client_id status
------------------
67 1
67 0
67 0
67 0
77 0
我只需要获取那些 client_id
的 latest (top)
条目是 0
。
我尝试关注,但都得到了 67 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
如何设置条件,以便我只能获取那些 status
为 0 的记录?
使用不存在的相关子查询
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')
要获取最新条目,您可以使用相关子查询:
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
用于您想要的过滤。
请尝试以下一种,我认为它会解决您的问题。
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
我有一个结果集如下:
client_id status
------------------
67 1
67 0
67 0
67 0
77 0
我只需要获取那些 client_id
的 latest (top)
条目是 0
。
我尝试关注,但都得到了 67 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
如何设置条件,以便我只能获取那些 status
为 0 的记录?
使用不存在的相关子查询
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')
要获取最新条目,您可以使用相关子查询:
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
用于您想要的过滤。
请尝试以下一种,我认为它会解决您的问题。
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