0

如果 ProjectStatusType.Name 不为空,则以下 SQL 将按预期工作。因此,我放置了用“未指定”替换空值的 case 语句。我想要做的是添加一个 where 语句来显示 ProjectStatusType.Name = 'Not Specified',但没有返回任何数据,尽管数据库中有一条带有 null projectstatustype.name 的记录。请指教; 还有什么方法,或者我该如何修复 SQL 查询?

SELECT PersonResponsible.Name AS TeamLeaderName,
       CASE
           WHEN ProjectStatusType.Name IS NULL THEN 'Not Specified'
           ELSE COALESCE(ProjectStatusType.Name, '')
       END AS ProjectStatusName,
       Project.ProjectTitle AS Title,
       ProjectStatus.DateStatus,
       Project.ProjectId,
       Project.ContactName,
       BusinessDivision.Name AS BusinessUnit,
       BusinessUnit.Name AS WorkSection,
       ProjectSubGroup.Name AS ProjectSubGroupName,
       ProjectGroup.Name AS ProjectGroupName,
       Project.DateRequested
FROM BusinessUnit
INNER JOIN BusinessDivision ON BusinessUnit.BusinessDivisionId = BusinessDivision.BusinessDivisionId
INNER JOIN ProjectCode ON BusinessUnit.BusinessUnitId = ProjectCode.BusinessUnitId
RIGHT OUTER JOIN Project
INNER JOIN ProjectSubGroup ON Project.ProjectSubGroupId = ProjectSubGroup.ProjectSubGroupId
INNER JOIN ProjectGroup ON ProjectSubGroup.ProjectGroupId = ProjectGroup.ProjectGroupId ON ProjectCode.ProjectCodeId = Project.ProjectCodeId
LEFT OUTER JOIN PersonResponsible ON Project.PersonResponsibleId = PersonResponsible.PersonResponsibleId FULL
OUTER JOIN ProjectStatusType
INNER JOIN ProjectStatus ON ProjectStatusType.ProjectStatusTypeId = ProjectStatus.ProjectStatusTypeId
AND ProjectStatus.ProjectStatusId IN
  (SELECT MAX(ProjectStatusId) AS ProjectStatusId
   FROM ProjectStatus
   GROUP BY ProjectId) ON Project.ProjectId = ProjectStatus.ProjectId
WHERE ProjectStatus ProjectStatusType.Name ='Not Specified'
4

2 回答 2

0

两点:

首先,检查 null 的 CASE 对 COALESCE 表达式来说似乎是多余的。

这应该更简单:

SELECT COALESCE(ProjectStatusType.Name, 'Not Specified') AS ProjectStatusName

其次,比较ProjectStatusType.Name(表中的值)与比较ProjectStatusName(您选择的值)不同。

尝试更接近此的 WHERE 子句:

WHERE ProjectStatusName = 'Not Specified'
于 2013-09-10T00:05:18.627 回答
0

这是Itzik Ben-Gan提供的关于 SQL 服务器如何处理查询的精彩图表。顺序与我们编写 T-SQL 的方式不同。

因此,rutter 的解决方案可能会错过空字符串。

如果我经常执行这种类型的业务逻辑,我会编写一个函数,该函数将采用空字符串或空值并返回一个字符串“未知”。在查询中调用此函数并按“未知”过滤。

下面的示例创建一个临时表,将数据加载到表中,并返回转换为调整名称“未指定”的空字符串和空值。

我希望这有帮助。

当查询不按我认为应该的方式工作时,我总是参考逻辑处理图表。

祝你好运

约翰

-- 
-- Logical query processing
--

-- From, Where, Group By, Having, Select (expression, distince, top), order by

-- sample table
create table #status
( id int identity(1,1),
  name varchar(50) null
);

-- Sample data
insert into #status values
(''),
(null),
('www.craftydba.com');


-- Return rows with null or empty string
select 
    case when ltrim(name) = '' then 'Not Specified'
    else coalesce(name, 'Not Specified') end as adjusted_named, 
    name
from #status 
where 
  ltrim(name) = '' or 
  coalesce(name, 'Not Specified') = 'Not Specified';
于 2013-09-10T00:39:46.517 回答