3

我一直在研究从 5 个不同的表中选择的查询:

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

这是结果在视觉上的样子: 在此处输入图像描述

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

在此处输入图像描述

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

每天只能进入 1 次。

我怎样才能做到这一点?

4

1 回答 1

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

于 2013-09-16T20:21:53.123 回答