0

我的查询

Declare     @From       DateTime='01 Feb 2013'
Declare     @To         DateTime='28 Feb 2013 23:59:59'

Select 
            Case
                  When
                  (
                        Select TOP 1 f1.UpdatedOn
                        From TicketTypeFollowUp As f1 with(nolock)
                        Where f1.UpdatedOn<T.UpdatedOn And f1.Ticket=T.Ticket
                        Order By f1.UpdatedOn Desc
                  )IS Null
                  Then Ticket.TicketRaisedOn

                  Else
                  (
                       Select TOP 1 f1.UpdatedOn
                       From TicketTypeFollowUp As f1 with(nolock)
                       Where f1.UpdatedOn<T.UpdatedOn And f1.Ticket=T.Ticket
                       Order By f1.UpdatedOn Desc
                  ) End [Start Date]

      From dbo.TicketTypeFollowUp T with(nolock)
      --Some Tables Omitted          
      Where CAST(TicketRaisedOn As Date)Between ''+Convert(VarChar(19), @From, 100)+''       And ''+Convert(VarChar(19), @To, 100)+''

如果 Column[Start Date]的值大于@ToThen @ToValue 应该打印 Else [Start Date] Column

我怎样才能在同一个查询中写它?

我试过的

       Case When(
             Case
                  When
                  (
                        Select TOP 1 f1.UpdatedOn
                        From TicketTypeFollowUp As f1 with(nolock)
                        Where f1.UpdatedOn<T.UpdatedOn And f1.Ticket=T.Ticket
                        Order By f1.UpdatedOn Desc
                  )IS Null
                  Then Ticket.TicketRaisedOn

                  Else
                  (
                       Select TOP 1 f1.UpdatedOn
                       From TicketTypeFollowUp As f1 with(nolock)
                       Where f1.UpdatedOn<T.UpdatedOn And f1.Ticket=T.Ticket
                       Order By f1.UpdatedOn Desc
                  ) End [Start Date]
              )> @To Then @To Else [Start Date] End,

数据库:SQL 服务器 2008

4

1 回答 1

2

在我看来你需要这个:

Declare     @From       DateTime='01 Feb 2013'
Declare     @To         DateTime='28 Feb 2013 23:59:59'

Select CASE WHEN ISNULL(StartDates.[Start Date], Ticket.TicketRaisedOn) > @To THEN @To ELSE ISNULL(StartDates.[Start Date], Ticket.TicketRaisedOn) END AS ResultValue
From dbo.TicketTypeFollowUp T with(nolock)
    --Some Tables Omitted 
    OUTER APPLY
    (
        Select TOP 1 f1.UpdatedOn AS [Start Date]
        From TicketTypeFollowUp As f1 with(nolock)
        Where f1.UpdatedOn<T.UpdatedOn And f1.Ticket=T.Ticket
        Order By f1.UpdatedOn Desc
    ) StartDates
Where CAST(TicketRaisedOn As Date)Between ''+Convert(VarChar(19), @From, 100)+''       And ''+Convert(VarChar(19), @To, 100)+''

OUTER APPLY 允许您指定每行的计算值,引用来自上面连接表的值,但之后它就像来自 JOIN 的数据。所以你给你的 APPLY 一个别名,就好像它是一个表一样,然后根据上面的需要多次访问它的值。

如您所见,这极大地简化了您的查询——应用在您的工具带中非常方便。)))

编辑为每条评论添加了另一个 ISNULL。

于 2013-05-09T17:55:37.037 回答