SQL Server 2014上的GROUP BY和HAVING子句存在一個奇怪的問題。帶有HAVING子句的GROUP BY不會返回一行嗎?
這顯然有可能我做了錯誤的事情,但我無法理解這一點。
這裏的設置數據:
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)
這返回單行...爲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
然而,不知何故以下不返回任何行......我基本上要求它給我從最大日期第一個查詢。爲什麼會這樣?
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
然而,它不返回行......感到困惑。
SQL小提琴這裏:
http://sqlfiddle.com/#!6/5e44cb/1
自從他向我展示什麼是第一個錯誤以後,讓dognose贏得了勝利......可能會採用CTE方法。 –