查询最近的活动是失败的

时间:2013-11-05 19:55:44

标签: postgresql

我考虑过相关的帖子而无法获得成功。我需要有一个报告,显示客户的最后一个注释。我非常接近,但查询通常“错过”实际的最后一个条目。假设我运行报告显示过去6个月的最后一个条目,并显示“bob”的最后一个条目为8/1/13。当我在桌子上看时,有一张关于10/23/13的便条。我检查了看数据是否搞砸了,但看起来不错。如果有人能说清楚为什么我在查询中有一些“几乎最后的注释”而不是实际的最新注释,我会非常感激。这是我用的评论解释它的查询:

SELECT  
DISTINCT ON (c.client_id) --the client id
g.name, -- the office location
MAX (n.date_service),
n.date_creation, 
sv.code, -- the service / activity code
c.name_lastfirst_cs, -- client's name
n.date_service,  
s.staff_id -- staff id
FROM  notes n, clients c, services sv,  staff s, groups g
WHERE n.zrud_service = sv.zzud_service
AND n.visibility_flag = '1' -- 1 = valid note
AND n.zrud_client = c.zzud_client
AND n.zrud_staff = s.zzud_staff
AND n.zrud_group = g.zzud_group
AND g.name = 'HALIFAX' -- am specifying a single location

-- the next 4 lines were an attempt to query specific time range and actitity codes
--AND s.code IN ('10101', '10102', '10201',     10202','10203','10204','10205','10401','10402','10403','10405')
-- AND n.date_service >= '1/1/2010'
-- AND n.date_service<= '11/7/2013'
-- AND n.date_service BETWEEN (now() - '800 days'::interval)::timestamp AND now() 

GROUP BY g.name,sv.code, c.client_id, c.name_lastfirst_cs, s.staff_id,
n.date_service, n.date_creation

1 个答案:

答案 0 :(得分:1)

当您希望在表格中使用some_date的最后一个条目时,将DISTINCT ONORDER BY some_date DESC一起使用是一个不错的选择:

SELECT  
DISTINCT ON (c.client_id) --the client id
g.name, -- the office location
n.date_service,
n.date_creation, 
sv.code, -- the service / activity code
c.name_lastfirst_cs, -- client's name
n.date_service,  
s.staff_id -- staff id
FROM  notes n, clients c, services sv,  staff s, groups g
WHERE n.zrud_service = sv.zzud_service
AND n.visibility_flag = '1' -- 1 = valid note
AND n.zrud_client = c.zzud_client
AND n.zrud_staff = s.zzud_staff
AND n.zrud_group = g.zzud_group
AND g.name = 'HALIFAX' -- am specifying a single location
ORDER BY c.client_id, n.date_service DESC;

请注意,不需要GROUP BY也不需要MAXDISTINCT ON负责分组,ORDER BY只检索最后一个条目。