在特定列中组合具有相同值的行

时间:2014-01-08 21:03:22

标签: sql sql-server

我正在处理一个查询但是StoryNumber会以多行的形式返回。

以下是查询:

SELECT 
    STY.[Number] StoryNumber
    ,ISNULL(SUM(DTH.[Hours]), 0) AS WorkHours
    ,MAX(CASE 
            WHEN DTH.Hours != 0
                THEN DTH.ActivityDate
            END) AS LatestActivityDate
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
GROUP BY LEN(STY.[Number])
    ,STY.[Number]
    ,TSK.[Name]

此查询实际上已简化,并且所有JOIN条件都是必需的。

这是上述查询的输出:

enter image description here

我如何组合StoryNumber和当有多个诸如OHC-1总和工作时间并找到最高活动日期?

1 个答案:

答案 0 :(得分:2)

GROUP BY中删除无关字段:

SELECT STY.[Number] StoryNumber
      ,ISNULL(SUM(DTH.[Hours]), 0) AS WorkHours
      ,MAX(CASE WHEN DTH.Hours != 0
                THEN DTH.ActivityDate
           END) AS LatestActivityDate
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
LEFT JOIN [User] USR ON TSK.PointPerson = USR.DisplayName
GROUP BY STY.[Number]