2

我有一个表格,我们可以在其中有多个条目的相同票号。我想根据 Initiated on 列检索最近的票号(相同票号)。

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)'`
4

6 回答 6

2

此问题的一般解决方案(适用于任何数据库)如下:

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 获取所有值,其中没有具有相同TicketID 和更新日期的票证。

笔记:

  • 如果有两张“最近”的票具有相同的InitiatedOn价值,这可能会返回重复。
  • 确保在TicketInitiatedOn列上都有适当的索引
于 2012-08-13T08:35:36.433 回答
1

试试这个:

这将提供每个组的最新记录

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
于 2012-08-13T08:34:20.720 回答
1
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
于 2012-08-13T08:36:17.997 回答
0

如果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
于 2012-08-13T08:34:56.520 回答
0
Select t1.* 
from tickets t1 
left join tickets t2 on (t1.ticket = t2.ticket and t2.initiatedon > t1.initiatedon)
where t2.ticket is null;
于 2012-08-13T08:36:13.040 回答
-1
select * from table where ticket=199485 order by InitiatedOn desc limit 1;
于 2012-08-13T08:34:14.203 回答