如何找到未关闭的最旧票?

时间:2015-09-23 17:51:30

标签: sql sql-server

我有一张桌子:

Ticket #      SubmitDate    Status
    101        1/1/2015     Closed
    102        1/1/2015     Closed
    103        1/1/2015     Closed
    104        1/2/2015      Open
    105        1/2/2015     Closed
    106        1/2/2015      Open
    107        1/2/2015      Open
    108        1/2/2015     Closed
    109        1/3/2015     Closed
    110        1/4/2015      Open
    111        1/5/2015     Closed
    112        1/5/2015     Closed
    113        1/5/2015      Open
    114        1/5/2015      Open
    115        1/5/2015      Open

我正在努力寻找仍然开放的最旧票。 我知道MIN(SubmitDate)会得到我最早的SubmitDate,但我无法将查询放在一起。

新编辑: 大家好。我正在修改这个问题,所以更清楚。我向任何认为令人困惑的人道歉。我很有压力要立即得到答案,所以我太匆忙地贴了它。

我正在尝试确定仍处于“打开”状态的最旧票证#。 我一切都错了:

以下是我失败的查询之一:

SELECT

MIN(SubmitDate) as [Date Submitted]
,(SELECT FROM TicketTable WHERE Status = 'Open' AND SubmitDate = MIN(SubmitDate)) as [Ticket #]
,Status as [Status]

FROM TicketTable

我想要达到的结果是:

Date Submitted  Ticket #    Status
1/2/2015          104        Open

我再次道歉。我从来没有打算简单地得到答案。我只是希望有一丝暗示。再次感谢所有人。

6 个答案:

答案 0 :(得分:14)

select top 1 * from table
where "status" = 'Open'
order by "SubmitDate" asc ;

在SQL Server 2012+版本中,您还可以使用(标准)offset - fetch语法替换top

select * from table
where "status" = 'Open'
order by "SubmitDate" asc 
offset 0 rows
fetch first 1 row only ;

答案 1 :(得分:3)

select top 1 * from Table where Status = 'Open' order by SubmitDate desc 

答案 2 :(得分:1)

row_number()上使用order bySubmitDate条款就行了。

select SubmitDate, [Ticket #], Status
  from (select t.*,
               row_number() over (order by SubmitDate) as rn
          from mytable t
         where t.Status = 'Open') x
 where x.rn = 1

答案 3 :(得分:1)

如您所见,您的大部分答案都是这种格式。我个人认为这是最直接的前进,因为它说的是混淆嵌套查询和使用分钟。

SELECT TOP 1 * 
FROM 
    YourTable 
WHERE 
    Status = 'Open'
ORDER BY
    SubmitDate Desc

答案 4 :(得分:-1)

<强> SQL Fiddle Demo

SELECT *
FROM YourTable Y,
    (SELECT  MIN(SubmitDate) mDate
    FROM YourTable
    WHERE Status = 'Open') as T
WHERE Y.SubmitDate = T.mDate
  AND Status = 'Open'

答案 5 :(得分:-1)

我只需要在已经很棒的列表中添加另一个:

SELECT * 
FROM table
WHERE submitDate IN (SELECT min(SubmitDate) FROM table WHERE status = 'Open')

但就个人而言,我会选择SELECT TOP 1...路线的@ STB,因为这很可能是该组中表现最佳的。其余的将依赖于子查询,这意味着DB(包括这一个)两次击中表。

但是......只是想分享一下,有很多方法可以解决这个问题