我正在尝试检索已超过某个事件的表格中的最新条目。此关注的主表包含用户的ID,发生的事件类型以及时间戳。
这就是我目前所在的地方:
function playBeep() {
var sound = document.getElementById("Sound")
sound.play();
window.location.href = '/'; //Go to HomePage
}
这个输出给了我以前的所有事件(虽然没有针对个别事件的欺骗,我假设)。我现在正在寻找一种方法来获取RefNo,Subcase,EventDate和EventCode的每个组合的最新版本。
答案 0 :(得分:2)
未经测试,但与WITH TIES
一致的Row_Number()
条款可能会对此有所帮助
SELECT Top 1 with ties
cc.RefNo
,cc.Subcase
,ev.EventDate
,evt.EventCode
,ev.Amount
,previousevent.EventCode as [previous Event]
,previousevent.previousdate as [date previous event]
FROM event ev JOIN EventTemplate evt ON ev.EventTemplateID = evt.ID
JOIN CCase cc ON cc.ID = ev.CCaseID
JOIN (SELECT MAX(ev.EventDate) as previousdate, evt.EventCode, CCaseID
FROM Event ev JOIN EventTemplate evt ON ev.EventTemplateID = evt.ID
WHERE (evt.EventCode LIKE 'SI%' OR evt.EventCode LIKE 'SM%')
Group by CCaseID, evt.EventCode) as previousevent
ON previousevent.CCaseID = cc.ID
AND previousevent.previousdate < ev.EventDate
Order By Row_Number() over (Partition By RefNo, Subcase, EventCode Order By EventDate Desc)
答案 1 :(得分:1)
可能最简单的方法是使用cte和row_number:
;WITH CTE AS
(
SELECT cc.RefNo
,cc.Subcase
,ev.EventDate
,evt.EventCode
,ev.Amount
,previousevent.EventCode as [previous Event]
,previousevent.previousdate as [date previous event]
, ROW_NUMBER() OVER (PARTITION BY cc.RefNo ,cc.Subcase ,ev.EventDate, evt.EventCode ORDER BY previousevent.previousdate DESC) AS rn
FROM event ev JOIN EventTemplate evt ON ev.EventTemplateID = evt.ID
JOIN CCase cc ON cc.ID = ev.CCaseID
JOIN (SELECT MAX(ev.EventDate) as previousdate, evt.EventCode, CCaseID
FROM Event ev JOIN EventTemplate evt ON ev.EventTemplateID = evt.ID
WHERE (evt.EventCode LIKE 'SI%' OR evt.EventCode LIKE 'SM%')
Group by CCaseID, evt.EventCode) as previousevent
ON previousevent.CCaseID = cc.ID
AND previousevent.previousdate < ev.EventDate
)
SELECT cc.RefNo
,cc.Subcase
,ev.EventDate
,evt.EventCode
,ev.Amount
,previousevent.EventCode as [previous Event]
,previousevent.previousdate as [date previous event]
FROM CTE
WHERE rn = 1