GROUP BY with HAVING 子句没有return 一行?

GROUP BY with HAVING clause does not return a row?

SQL Server 2014 上的 GROUP BY 和 HAVING 子句出现奇怪问题。

很可能我做错了什么,但我无法理解这一点。

设置数据如下:

create table #accounts(accountid int)
create table #data(accountid int, categoryid int, asofdate date, datavalue numeric(20, 10))

insert into #accounts
    values 
    (1),(2),(3)

insert into #data
    values 
    (1, 10, '1/31/2015', 0),
    (1, 10, '2/28/2015', 10),
    (1, 10, '3/31/2015', 20),
    (2, 10, '1/31/2015', 0),
    (2, 10, '2/28/2015', 15),
    (2, 10, '3/31/2015', 25),
    (3, 10, '1/31/2015', 0),
    (3, 10, '2/28/2015', 7),
    (3, 10, '3/31/2015', 12)

这 return 是一行... 2015 年 1 月 31 日。唯一一个总数为零的日期

select categoryid, asofdate, sum(datavalue) as totalvalue
from #accounts a
inner join #data d
    on d.accountid = a.accountid
group by d.categoryid, d.asofdate
having sum(datavalue) = 0

结果是 10, '1/31/2015', 0

然而,不知何故以下没有 return 任何行......我基本上是要求它给我第一个查询的最大日期。为什么会犹豫?

select categoryid, max(asofdate) as MaxAsOfDate, sum(datavalue) as totalvalue
from #accounts a
inner join #data d
    on d.accountid = a.accountid
group by d.categoryid
having sum(datavalue) = 0

drop table #accounts
drop table #data

然而 return 没有行...感到困惑。

SQL Fiddle 这里:

http://sqlfiddle.com/#!6/5e44cb/1

通过删除 GROUP BY asOfDate,您已删除所有 SUM()=0 的组。

您应该使您的第一个查询成为派生的 table 或 CTE,然后在其外部执行 MAX 以获得您想要的结果。

简单地说,因为您按 d.categoryid 分组 - 而且没有按此列分组,return 0 对于 sum(datavalue)http://sqlfiddle.com/#!6/5e44cb/4(89)

如果您可以将您的预期输出添加到您的post,我们也许能够帮助您完成您需要的查询。