如果特定列为NULL,则在同一表中以不同方式返回数据行

时间:2013-09-17 20:50:33

标签: sql sql-server

我一直致力于查询:

SELECT D.PointPerson AS Person, R.[Name] AS Project, ISNULL(P.[Name]+' - '+P.[Description], 'KanBan') AS Sprint, S.[Number] AS Story, T.[Name] AS Task,
   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,
   sum(D.[Hours]) AS Total
FROM DailyTaskHours D
INNER JOIN Task T ON D.TaskId = T.PK_Task 
INNER JOIN Story S ON T.StoryId = S.PK_Story 
LEFT JOIN Sprint P ON S.SprintId = P.PK_Sprint 
INNER JOIN Product R ON S.ProductId = R.PK_Product
GROUP BY D.PointPerson, R.[Name], P.[Name], P.[Description], S.[Number], T.[Name]
ORDER BY CASE WHEN ISNULL(P.[Name]+' - '+P.[Description], 'KanBan') = 'KanBan'
    THEN 1
    ELSE 0 END,
    Project ASC,
    Sprint ASC,
    Story ASC,
    Task ASC

正如您所看到的,它将许多表列组合在一起。

有两个表与基表(DailyTaskHours)有关系:

enter image description here

目前,我的查询检索上述架构右侧的所有关系。在所有这些情况下,DailyTaskHours中的列NonScrumStoryId为NULL。作为同一查询的一部分,我想返回所有DailyTaskHours条目,包括NonScrumSoryId为NULL的条目。在这种情况下,没有与Task,Story,Sprint或Product表的连接。

以下是目前的表格: enter image description here

因此,如果该行是NonScrumStory行,即该行中的列isnt为null,则会填充下表,但Project,Sprint和Task都将为NULL。故事将取自NonScrumStory.IncidentNumber

我将如何做到这一点?

2 个答案:

答案 0 :(得分:2)

更改

INNER JOIN Task T ON D.TaskId = T.PK_Task 

LEFT JOIN Task T ON D.TaskId = T.PK_Task 

当LE子连接在join子句中不匹配时,它们不会从from子句中的表中删除行。

此外,向NonScrumStoryId添加左连接,然后将您的选择更改为:

COALESCE(S.[Number], NonScrumStoryId.IncidentNumber)

COLLASCE检查第一个争论是否为空,如果是,则返回第二个争论。在这种情况下,如果故事为空,它将返回IncidentNumber。

答案 1 :(得分:1)

你的意思是这样的:

CASE
WHEN S.[Number] is null
THEN NonScrumStory.IncidentNumber
ELSE S.[Number]
END
as Story

?用此替换Story-field的定义并尝试...