获取另一列不等于零的列的最大日期

时间:2013-12-16 15:13:14

标签: sql sql-server

我正在尝试获取用户提供活动的最新活动日期作为查询的一部分。这是查询:

USE SCRUMAPI2

DECLARE @userParam VARCHAR(100)
    ,@statusParam VARCHAR(100)

SET @userParam = '%'
SET @statusParam = '%'

SELECT ROW_NUMBER() OVER (
        ORDER BY TSK.[Status] DESC
        ) AS 'RowNumber'
    ,PDT.[Name] AS Project
    ,(
        CASE WHEN (
                    STY.KanBanProductId IS NOT NULL
                    AND STY.SprintId IS NULL
                    ) THEN 'KanBan' WHEN (
                    STY.KanBanProductId IS NULL
                    AND STY.SprintId IS NOT NULL
                    ) THEN 'Sprint' END
        ) AS ProjectType
    ,STY.[Number] StoryNumber
    ,STY.Title AS StoryTitle
    ,TSK.[Name] AS Task
    ,CONVERT(VARCHAR(20), STY.Effort) AS Effort
    ,CONVERT(VARCHAR(20), TSK.OriginalEstimateHours) AS OriginalEstimateHours
    ,ISNULL(SUM(DTH.[Hours]), 0) AS [TotalHours]
    ,TSK.[Status] AS [Status]
FROM Task TSK
LEFT JOIN DailyTaskHours DTH ON TSK.PK_Task = DTH.TaskId
LEFT JOIN Story STY ON TSK.StoryId = STY.PK_Story
LEFT JOIN Sprint SPT ON STY.SprintId = SPT.PK_Sprint
LEFT JOIN Product PDT ON STY.ProductId = PDT.PK_Product
WHERE TSK.PointPerson LIKE @userParam
    AND TSK.[Status] LIKE @statusParam
GROUP BY LEN(STY.[Number])
    ,STY.[Number]
    ,TSK.[Status]
    ,STY.Title
    ,PDT.[Name]
    ,TSK.CreateDate
    ,TSK.[Name]
    ,STY.KanBanProductId
    ,STY.SprintId
    ,TSK.OriginalEstimateHours
    ,STY.Effort
ORDER BY CASE TSK.[Status] WHEN 'Not Started' THEN 1 WHEN 'In Progress' THEN 2 WHEN 'Impeded' THEN 3 WHEN 'Done' THEN 4 END

我想添加一行功能如下:

,MAX(DTH.ActivityDate WHERE DTH.Hours != 0) AS LatestActivityDate

然而,这会导致语法错误。我无法将DTH.Hours!= 0添加到WHERE语句中,因为我不希望整个查询被它过滤。那么如何获得最近的ActivityDate,其中小时数不等于零?

以下是DTH表的参考内容:

enter image description here

1 个答案:

答案 0 :(得分:3)

CASE expression是我们的朋友:

MAX(CASE WHEN DTH.Hours != 0 THEN DTH.ActivityDate END) AS LatestActivityDate