我有表中,我们可以有同一张票no.for多个entries.i要根据发起了关于列号来获取最新的票(编号相同的票)。
Ticket VendorTicket InitiatedOn Comments
198165 test 2012-08-10 16:31:33.707 test
199485 sagar 2012-08-11 12:36:25.720 sagar
199485 sagar1 2012-08-11 14:36:25.720 sagar1
199478 kishor 2012-08-11 12:37:21.923 kishor
我写了这个查询在T-SQL存储过程中它给了我错误说xObj = {"Incorrect syntax near '.'."}
我的T-SQL
`@SQL='Select ''<a href="javascript:editTicketByIDAction('' + CONVERT(VarChar(Max), Ticket) + '')">'' + CONVERT(VarChar(Max),Ticket) + ''</a>'' t1.Ticket,t1.VendorTicket[Vendor Ticket],t1.Comments
From VendorTickets t1
WHERE NotifyOn <= GetDate() And NotifyOn Is Not Null AND
NOT EXISTS
(SELECT * FROM VendorTickets t2
WHERE t1.Ticket = t2.Ticket AND t1.InitiatedOn < t2.InitiatedOn)'`
一般的解决方案(适用于任何数据库)对这个问题如下:
SELECT * FROM [my_table] t1
WHERE NOT EXISTS (
SELECT * FROM [my_table] t2
WHERE t1.Ticket = t2.Ticket
AND t1.InitiatedOn < t2.InitiatedOn
)
这种读取:从MY_TABLE所有值那里是用相同的无人售票Ticket
ID和更近的日期。
笔记:
- 这可能会返回重复的情况下,有两个“最近的”入场券具有相同
InitiatedOn
值。 - 一定要对双方合适的索引
Ticket
和InitiatedOn
列
尝试这个:
这将给最近的记录各组
select * from <table> t join
(select Ticket,max(InitiatedOn) as InitiatedOn
from <table>
group by Ticket)a
on t.Ticket=a.Ticket
and t.InitiatedOn=a.InitiatedOn
SELECT Ticket,
VendorTicket,
InitiatedOn,
Comments
FROM (
SELECT Ticket,
VendorTicket,
InitiatedOn,
Comments,
ROW_NUMBER() OVER (PARTITION BY Ticket ORDER BY InitiatedOn DESC) AS Row
FROM Table
) AS Q
WHERE Q.Row = 1
如果row_number() over()
是供您使用。
select T.Ticket,
T.VendorTicket,
T.InitiatedOn,
T.Comments
from (
select Ticket,
VendorTicket,
InitiatedOn,
Comments,
row_number() over(partition by Ticket order by InitiatedOn desc) as rn
from YourTable
) T
where T.rn = 1
Select t1.*
from tickets t1
left join tickets t2 on (t1.ticket = t2.ticket and t2.initiatedon > t1.initiatedon)
where t2.ticket is null;
select * from table where ticket=199485 order by InitiatedOn desc limit 1;