1

在我的 SQL 查询中,我正在使用CASE WHEN THEN ELSE END条件计算列值。现在我想找到计算列和普通列之间的区别

我的查询

SELECT  T.Ticket [Ticket],
        TT.TicketType [Ticket Type],
        T.Dependency [Dependency],
        CASE 
                WHEN (
                        SELECT  TOP 1 f1.UpdatedOn
                        FROM    TicketTypeFollowUp AS f1
                        WHERE   f1.UpdatedOn < T.UpdatedOn
                                AND f1.Ticket = 61423
                        ORDER   BY f1.UpdatedOn DESC
                    ) IS NULL
                THEN Ticket.TicketRaisedOn
                ELSE (
                        SELECT  TOP 1 f1.UpdatedOn
                        FROM    TicketTypeFollowUp AS f1
                        WHERE   f1.UpdatedOn < T.UpdatedOn
                                AND f1.Ticket = 61423
                        ORDER   BY f1.UpdatedOn DESC
                    )
                END [Start Date],
        T.UpdatedOn [End Date],
        L.EmpName [Updated By]
FROM    dbo.TicketTypeFollowUp T
        LEFT JOIN dbo.Ticket
                ON T.Ticket = Ticket.Code
        LEFT JOIN dbo.TicketType TT
                ON T.TicketType = TT.Code
        LEFT JOIN LoginUser L
                ON T.UpdatedBy = L.Code
WHERE Ticket = 61423

查询结果

Ticket  Type    Dependency  Start Date              End Date                Updated By
61423   FLM     AGS         2013-01-22 15:50:08.757 2013-01-22 18:35:50.893 Kedar S

我想要一个显示End Time - Start Time我使用过的列,CASE因此我无法计算差异。

数据库是 SQL SERVER 2008

4

2 回答 2

2
with lastUpdate(ticket, lastUpdate) as (
        select  ticket,
                max(updateOn)
        from    TicketTypeFollowUp
        group by ticket)
SELECT  T.Ticket [Ticket],
        TT.TicketType [Ticket Type],
        T.Dependency [Dependency],
        coalesce(lastUpdate, ticketRaisedOn) [Start Date],
        T.UpdatedOn [End Date],
        datediff(mi, coalesce(lastUpdate, ticketRaisedOn), T.UpdatedOn) durationMins,
        L.EmpName [Updated By]
FROM    dbo.TicketTypeFollowUp T
        LEFT JOIN dbo.Ticket
                ON T.Ticket = Ticket.Code
        LEFT JOIN dbo.TicketType TT
                ON T.TicketType = TT.Code
        LEFT JOIN LoginUser L
                ON T.UpdatedBy = L.Code
        left join lastUpdate lu on t.ticket = lu.ticket
WHERE Ticket = 61423
于 2013-01-22T13:56:15.423 回答
1

您可以将当前查询用作 CTE 或派生表。以下是使用 CTE 的示例:

;WITH CTE AS
(
    -- your current query here
)
SELECT *, DATEDIFF(MINUTE,[Start Date],[End Date]) [End Time - Start Time]
FROM CTE
于 2013-01-22T14:01:19.027 回答