0

如果我将以下值插入到我的表中

Insert into Table1 (Field1, Field2, Field3, Field4, DateField) values (1, 1, 100, 5, "5/10/2012")
Insert into Table1 (Field1, Field2, Field3, Field4, DateField) values (1, 2, 100, 99, "5/10/2012")
Insert into Table1 (Field1, Field2, Field3, Field4, DateField) values (1, 3, 100, 3, "5/10/2012")

我的查询将尝试获取的是来自 Field4 的值,在某个日期之前 Field2 中的最大值。

例子

select isnull(Field4,0) from Table1 
where Field1 = 1 and Field3 = 100 and datediff(day,DateField,"5/21/2012") > 0
having Max(Field2) = Field2

效果很好。我得到3,这是预期的。现在这就是我的问题的来源。Field3 可能有其他值,例如 110。当我运行该查询时

select isnull(Field4,0) from Table1 
where Field1 = 1 and Field3 = 110 and datediff(day,DateField,"5/21/2012") > 0
having Max(Field2) = Field2

我没有得到任何结果。它应该为空,然后 isnull(Field4,0) 应该吐出 0。但事实并非如此。我尝试用 count(*) 替换选择以查看它是否返回 0,但它没有返回任何内容。我不知所措。我需要它返回 0,因为这将进入一个临时表,然后与另一个表中的值相加。谢谢。

编辑 - 新问题部分 我知道我在这里可能一直在使用 isnull 做错事。我可以接受。但是,如果我想编写一个 case 语句来处理不返回的任何内容,那么如果没有返回任何行,它就不会返回 0。

select count(*) from Table1 
where Field1 = 1 and Field3 = 110 and datediff(day,DateField,"5/21/2012") > 0
having Max(Field2) = Field2

上面的代码没有返回任何东西,而不是像我想的那样返回 0 。

4

1 回答 1

1

您没有得到任何结果,因为您插入的 3 条记录中没有一条为 Field3 提供 110。因此,查询不会返回任何行。仅当这些值用于返回的行ISNULL而不是 5、99 或 3 时,才会使用您的值。NULL

如果此记录在您的表中:

INSERT INTO Table1 (Field1, Field2, Field3, Field4, DateField)
VALUES(1, 3, 110, NULL, "5/10/2012")

此记录将符合您的Field3 = 110要求,然后将 Field4 Null 设置为 0,您的 SELECT 逻辑将其设置为 0,但由于不是,因此您的查询不会返回任何内容。

第2部分

似乎HAVING正在从结果集中删除0记录,因为在子句之后没有留下任何记录WHERE来匹配HAVING条件。

如果您想查看是否有任何结果符合您的条件,可以使用EXISTS子句

IF EXISTS(
   SELECT COUNT(*)
   FROM Table1 AS t 
   WHERE t.Field1 = 1
      AND t.Field3 = 110 
      AND DATEDIFF(day, t.DateField, "5/21/2012") > 0
   HAVING MAX(Field2) = Field2
)
BEGIN
   --Code for when the record Exists
END
ELSE
BEGIN
   --No records logic here
END
于 2012-06-28T17:08:38.103 回答