sql查询中的嵌套Case语句

时间:2013-05-09 11:44:21

标签: sql sql-server sql-server-2008 case

我的查询

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)+''

如果列[Start Date]的值大于@To那么@To值应打印其他[开始日期]列

如何在同一个查询中编写它?

我尝试了什么

       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,

DB:SQL SERVER 2008

1 个答案:

答案 0 :(得分: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一个别名,好像它是一个表,然后根据需要多次访问它的值。

正如您所看到的,这大大简化了您的查询 - 在您的工具带中使用APPLY非常方便。)))

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