我创建了此代码以从我们的数据库中提取票证,并且还提取最后一个票据注释日期和最后一个票证用户。除非两个人(或更多)在最后一个日期创建了一个音符(无论时差),否则它将为每个票证创建多行。我该如何解决?这是代码:
Select distinct t.ticketID,
t.OpenDate,
c.categoryname,
s.statusname,
p.priorityname,
u.firstname,
u.lastname,
tu.firstname as 'tech_firstname',
tu.lastname as 'tech_lastname',
ltn.maxdate as 'last date',
ltu.firstname + ' ' + ltu.lastname as 'Last User'
from ticket t
left join category c on t.categoryid = c.categoryid
left join [status] s on t.statusid = s.statusid
left join [priority] p on t.priorityid = p.priorityid
left join [user] u on t.userid = u.userid
left join [user] tu on t.technicianid = tu.userid
left join ticketnote tn on t.ticketid = tn.ticketid
inner join (
Select Max(TicketNoteDate) as MaxDate, max(cast(ticketnotedate as time)) as MaxTime, ticketid, userid
From ticketNote
group by ticketid, userid) ltn on tn.ticketid = ltn.ticketid and tn.ticketnotedate = ltn.maxdate and cast(tn.ticketnotedate as time) = ltn.maxtime
left join [user] ltu on ltn.userid = ltu.userid
where t.statusid = 1
and t.LocationID = 1
order by t.ticketid
答案 0 :(得分:2)
根据评论中的建议,在您的子查询中使用row_number
获取maximum
值
SELECT row_number() over
(partition by tiketid, userid
order by TicketNoteDate desc ) as rn,
ticketid,
userid,
ticketnotedate
然后join
,外部查询条件为rn=1
答案 1 :(得分:0)
我重写了它获取所有票证的最大日期,然后查找具有该最大日期的所有票证,并按时间顺序排序并获得第一行,然后检索该条目的额外数据(如用户)。我无法测试这个,但是这里......
Select distinct t.ticketID,
t.OpenDate,
c.categoryname,
s.statusname,
p.priorityname,
u.firstname,
u.lastname,
tu.firstname as 'tech_firstname',
tu.lastname as 'tech_lastname',
ltn.maxdate as 'last date',
ltu.firstname + ' ' + ltu.lastname as 'Last User'
from ticket t
left join category c on t.categoryid = c.categoryid
left join [status] s on t.statusid = s.statusid
left join [priority] p on t.priorityid = p.priorityid
left join [user] u on t.userid = u.userid
left join [user] tu on t.technicianid = tu.userid
inner join (
select maxdate, maxtime, ticketid, userid, rownum from (
select maxdate, maxtime, ticketid, userid, row_number() over (order by maxdate desc, maxtime desc) as rownum
from ticketnote tn,
(Select Max(TicketNoteDate) as MaxDate
From ticketNote) mx
where mx.maxdate = tn.ticketnotedate
) x where x.rownum = 1
) ltn
left join [user] ltu on ltn.userid = ltu.userid
where t.statusid = 1
and t.LocationID = 1
order by t.ticketid