Sql server SQL Server 2012不工作时的情况

Sql server SQL Server 2012不工作时的情况,sql-server,tsql,sql-server-2012,case,Sql Server,Tsql,Sql Server 2012,Case,我的select语句中有这种情况,但它只显示a.InsertDate,即使该日期小于b.InsertDate。A4表格是我与之建立关系的表格的一部分 (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.A

我的select语句中有这种情况,但它只显示a.InsertDate,即使该日期小于b.InsertDate。A4表格是我与之建立关系的表格的一部分

(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 Server中运行良好,并且当您断言您正在比较的列都具有
datetime
类型时,我倾向于认为您错误地宣称您的查询“仅显示
a.InsertDate
,即使[该]日期[小于]b.InsertDate”(在此,我冒昧地解释您的要求,使您感到惊讶)

由于您没有提供任何数据,我们只能推测您可能是如何得到这样的错误印象的。然而,我观察到您是按
a.InsertDate
(降序)订购的然后从第一行选择结果。这将始终是最大值为
a.InsertDate
的行的结果。如果a.InsertDate>b.InsertDate,则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%'

您缺少一个“as[columnname]”最后。除此之外,它看起来还可以。那么那些
InsertDate
字段中实际有哪些值?它们是实际的日期/日期时间字段吗?如果它们只是varchar,并且您没有按照最重要的第一顺序存储日期字符串,那么您将得到字符串比较,并应用字符串比较规则,而不是日期比较规则。SQL
CASE
表达式在SQL Server 2012中运行良好。如果您得到的答案与您预期的不同,则可能是您的查询以其他方式被破坏,或者您的数据在某种程度上与您认为的不同。它正在比较键入的日期时间数据。我们需要样本数据、您获得的输出以及您希望能够帮助您实现的输出雷利。