1

我一直在处理一个查询:

SELECT P.[Name]+' - '+P.[Description] AS Sprint, S.[Number] AS Story, T.[Name] AS Task
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 
GROUP BY  P.[Name], P.[Description], S.[Number], T.[Name]

Sprint 列可能为 NULL,也可能不为 NULL:

在此处输入图像描述

如果有关联的 SprintId,上述查询将只返回请求的列。如果为 NULL,则不会返回整列。这是有道理的,当 S.SprintId = P.PK_Sprint 在 Story 表上为 NULL 时,它是不等价的。

如果它为 NULL,我仍然希望它返回包含所有其他表列数据的行,但使用 KanBan 一词而不是不返回任何内容。我如何实现这一目标?

4

3 回答 3

2

更改S.NumberISNULL(S.Number, 'KanBan')。如果在 Sprint 表中找不到匹配的 sprintID,这将添加“看板”。

更改INNER JOIN Sprint P ON S.SprintId = P.PK_SprintLEFT JOIN Sprint P ON S.SprintId = P.PK_Sprint。这确保了所有其他记录仍将显示,即使在不匹配的情况下也是如此。

然后完整的查询变为:

SELECT P.[Name]+' - '+P.[Description] AS Sprint, ISNULL(S.Number, 'KanBan') AS Story,     T.[Name] AS Task
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 
GROUP BY  P.[Name], P.[Description], S.[Number], T.[Name]
于 2013-09-17T14:01:10.603 回答
2
SELECT ISNULL(P.[Name]+' - '+P.[Description],'KanBan') AS Sprint, S.[Number] AS Story, T.[Name] AS Task
FROM DailyTaskHours D
INNER JOIN Task T ON D.TaskId = T.PK_Task 
INNER JOIN Story S ON T.StoryId = S.PK_Story 
LEFT OUTER JOIN Sprint P ON S.SprintId = P.PK_Sprint 
GROUP BY  P.[Name], P.[Description], S.[Number], T.[Name]
于 2013-09-17T14:01:15.603 回答
1

试试这个

  SELECT P.[Name]+' - '+P.[Description] AS Sprint, S.[Number] AS Story, T.[Name] AS Task
    FROM DailyTaskHours D
    INNER JOIN Task T ON D.TaskId = T.PK_Task 
    INNER JOIN Story S ON T.StoryId = S.PK_Story 
    LEFT OUTER JOIN Sprint P ON S.SprintId = P.PK_Sprint 
    GROUP BY  P.[Name], P.[Description], S.[Number], T.[Name]

请看一下内连接和外连接的区别

于 2013-09-17T14:00:43.413 回答