【问题标题】:SQL Server 2012 Case when not workingSQL Server 2012 不工作时的情况
【发布时间】:2016-05-20 00:51:20
【问题描述】:

我的选择语句中有这个案例,但即使日期小于 b.InsertDate,它也只显示 a.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]

【问题讨论】:

  • 您最后缺少一个“as [columnname]”。除此之外,它看起来还不错。
  • 那么InsertDate 字段中的实际值是什么?它们是实际的日期/日期时间字段吗?如果它们只是 varchar,并且您没有以最重要的优先顺序存储日期字符串,那么您会得到字符串比较,并且应用字符串比较规则,而不是日期比较规则。
  • SQL CASE 表达式在 SQL Server 2012 中运行良好。如果您得到的答案与您预期的不同,那么您的查询可能以其他方式被破坏,或者您的数据在某种程度上不是您认为的那样是。
  • 比较日期时间数据类型
  • 继续阅读how to post a T-SQL question on forums/StackOverflow。我们需要样本数据、您获得的输出以及您希望能够为您提供适当帮助的输出。

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


【解决方案1】:

由于CASE 表达式在 SQL Server 中工作正常,并且当您断言要比较的列都具有 datetime 类型时,我倾向于认为您错误地声称您的查询“仅显示a.InsertDate 即使 [那个] 日期 [小于] 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%'

【讨论】:

    猜你喜欢
    • 2014-12-11
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    相关资源
    最近更新 更多