将数据行与相同日期组合在一起

时间:2013-09-16 20:15:48

标签: sql sql-server

我一直致力于从5个不同的表中选择SELECTS:

SELECT  R.[Name],
        P.[Name],
        S.[Number],
        T.[Name],
        D.[Hours],
        D.[ActivityDate]
FROM DailyTaskHours D
INNER JOIN Task T
    ON D.TaskId = T.PK_Task
INNER JOIN Story S
    ON T.StoryId = S.PK_Story
INNER JOIN Sprint P
    ON S.SprintId = P.PK_Sprint
INNER JOIN Product R
    ON P.ProductId = R.PK_Product

这是结果在视觉上的样子: enter image description here

最后两列名为Hours和ActivityDate。从表中可以看出,对于Number - OPA-76,有两个条目:

enter image description here

我希望它不是两行,而是一行。我希望有7列,而不是最后两个标记为星期日到星期六,并且两个小时的条目根据他们的ActivityDate在一周的正确日期进行。

每天只能输入一次。

我该如何做到这一点?

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

SELECT R.[Name], P.[Name], S.[Number], T.[Name],
   sum(CASE WHEN DatePart(dw, D.ActivityDate) = 1 THEN D.[Hours] ELSE 0 END) AS Monday,
   sum(CASE WHEN DatePart(dw, D.ActivityDate) = 2 THEN D.[Hours] ELSE 0 END) AS Tuesday,
   sum(CASE WHEN DatePart(dw, D.ActivityDate) = 3 THEN D.[Hours] ELSE 0 END) AS Wednesday,
   sum(CASE WHEN DatePart(dw, D.ActivityDate) = 4 THEN D.[Hours] ELSE 0 END) AS Thursday,
   sum(CASE WHEN DatePart(dw, D.ActivityDate) = 5 THEN D.[Hours] ELSE 0 END) AS Friday,
   sum(CASE WHEN DatePart(dw, D.ActivityDate) = 6 THEN D.[Hours] ELSE 0 END) AS Saturday,
   sum(CASE WHEN DatePart(dw, D.ActivityDate) = 7 THEN D.[Hours] ELSE 0 END) AS Sunday
FROM DailyTaskHours D
INNER JOIN Task T ON D.TaskId = T.PK_Task
INNER JOIN Story S ON T.StoryId = S.PK_Story
INNER JOIN Sprint P ON S.SprintId = P.PK_Sprint
INNER JOIN Product R ON P.ProductId = R.PK_Product
GROUP BY R.[Name], P.[Name], S.[Number], T.[Name] 

请阅读有关工作日的说明:

http://technet.microsoft.com/en-us/library/aa258265(v=SQL.80).aspx