简体   繁体   English

通过最大日期和特定ID查找并返回最新记录

[英]Find and return the most recent record by max date and specific ID

What I am trying to do list the most recent event type '1081' 我正在尝试列出最新的事件类型“ 1081”

But I am only getting a '1081' if its the most recent event type. 但是,如果它是最新的事件类型,则只会得到“ 1081”。

The other event type is '1009' 其他事件类型为“ 1009”

If 1009 is the most recent event type then the record does not appear at all. 如果1009是最新的事件类型,则该记录根本不会出现。

If I search all event types then the number of records returned is correct. 如果我搜索所有事件类型,那么返回的记录数是正确的。

I have manually checked through the records and each has an event type 1081 attached to it. 我已经手动检查了记录,每个记录都附加了一个事件类型1081。

(The event type is matched to a comment that I want to display and I only want to display the most recent 1081 comment) (事件类型与我要显示的注释匹配,我只想显示最近的1081条注释)

This is the code 这是代码

SELECT
   o.SiteIdAndName,
   o.Id,
   r.callid,
   o.masterSymptom,
   o.subSymptom,
   o.received,
   o.closed,
   r.eventtype,
   r.datetime,
   r.loggedby,
   r.eventcomments,
   --o.lastedt,
   DATEDIFF(HOUR, received, COALESCE(closed, GETDATE())) AS 'HoursOpen'

FROM
   vw_UserView_OpenAndClosed2016 o
   LEFT JOIN dbo.tblcallev r ON r.callid = o.id --and r.eventtype = 1081

WHERE
   o.SchemeName = 'INDIS'
   AND o.SubSymptom = 'Care' 
   AND Closed is NULL
   AND r.datetime = (
   SELECT MAX(datetime)
   FROM dbo.tblcallevents
   WHERE NOT r.eventtype = 1009
   AND callid = r.callid
   )

Order by 
  r.eventtype

Can you help me at all? 你能帮我吗?

I think this could be very straight foreword query, like below 我认为这可能是非常简单的前言查询,如下所示

SELECT TOP(1) *--column list here
FROM
vw_UserView_OpenAndClosed2016 o
INNER JOIN dbo.tblcallev r ON r.callid = o.id and r.eventtype = 1081
WHERE o.SchemeName = 'INDIS' AND o.SubSymptom = 'Care' AND Closed is NULL
ORDER BY r.datetime

Here ORDER BY r.datetime will sort data according to recent datetime values for r.eventtype = 1081 在这里ORDER BY r.datetime将根据r.eventtype = 1081最新日期时间值对数据进行排序

UPDATED : 更新 :

;WITH CTE AS(
       SELECT *,
              ROW_NUMBER() OVER(PARTITION BY o.id ORDER BY r.datetime) RN  
       FROM
       vw_UserView_OpenAndClosed2016 o
       INNER JOIN dbo.tblcallev r ON r.callid = o.id and r.eventtype = 1081
       WHERE o.SchemeName = 'INDIS' AND o.SubSymptom = 'Care' AND Closed is NULL
)
SELECT * 
FROM CTE
WHERE RN=1 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM