SQL Server 2012不工作时的情况

时间:2016-02-09 21:05:01

标签: sql-server tsql sql-server-2012 case

我在select语句中有这个Case,但它只显示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]

1 个答案:

答案 0 :(得分:3)

由于CASE表达式在SQL Server中运行良好,并且当您断言要比较的列都具有datetime类型时,我倾向于认为您错误地声称您的查询“仅显示a.InsertDate即使[日期] [少于] b.InsertDate”(我可以自由地以一种让您惊讶的方式解释您的声明)。< / p>

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

在这种情况下,我不明白为什么要使用SELECT TOP查询而不是选择案例表达式的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%'