SQL Server 2012 不工作时的案例

SQL Server 2012 Case when not working

我的 select 声明中有这个案例,但它只显示 a.InsertDate,即使日期小于 b.InsertDate。 A4 table 是 table 我正在与之建立关系的一部分。

(select top 1 case when a.InsertDate > b.InsertDate then a.InsertDate else b.InsertDate end
        from tblAccount aa
        inner join tblContact c on aa.AccountID = c.AccountID
        inner join tblContactNote b on c.ContactID = b.ContactID
        inner join tblAccountNote a on aa.AccountID = a.AccountID
        where aa.AccountID = a4.AccountID and not a.Note like 'Account Assigned to%'
        order by a.InsertDate desc) [LastestDay]

因为 CASE 表达式在 SQL 服务器中工作正常,并且当您断言要比较的列都具有 datetime 类型时,我倾向于认为您错误地声称您的查询 "only shows the a.InsertDate even if [that] date is [less] than the b.InsertDate"(我可以自由地以一种让您感到惊讶的方式解释您的说法)。

由于您没有提供任何数据,我们只能推测您是如何产生这种错误印象的。但是,我观察到您按 a.InsertDate(降序)排序,然后从第一行中选择结果。这将始终是具有最大值 a.InsertDate 的行的结果。该行可能是也可能不是具有最大值 case when a.InsertDate > b.InsertDate then a.InsertDate else b.InsertDate end 的那一行。如果您真正想要的是 CASE 表达式的最大值,那么您的查询是错误的。

在那种情况下,我不明白您为什么要使用 SELECT TOP 查询而不是选择 case 表达式的 MAX() 值:

select
  max(case when a.InsertDate > b.InsertDate then a.InsertDate else b.InsertDate end)
from
  tblAccount aa
  inner join tblContact c on aa.AccountID = c.AccountID
  inner join tblContactNote b on c.ContactID = b.ContactID
  inner join tblAccountNote a on aa.AccountID = a.AccountID
where
  aa.AccountID = a4.AccountID
  and not a.Note like 'Account Assigned to%'