使用 SQL Server 2005,我尝试基于带有子查询的 case 语句进行分组,但出现错误(“每个 GROUP BY 表达式必须包含至少一个列引用。”)。我可以很容易地解决它,但是任何人都可以解释这个错误吗?我有一个对#header.header 的列引用。
create table #header (header int)
create table #detail (header int, detail int)
insert into #header values (1)
insert into #header values (2)
insert into #header values (3)
insert into #detail values (1, 1)
insert into #detail values (2, 1)
--error: Each GROUP BY expression must contain at least one column reference.
select case when exists (select 1 from #detail where #detail.header = #header.header) then 1 else 0 end hasrecords from #header
group by case when exists (select 1 from #detail where #detail.header = #header.header) then 1 else 0 end
--results I want
select hasrecords, count(*) from
(
select case when exists (select 1 from #detail where #detail.header = #header.header) then 1 else 0 end hasrecords from #header
) hasrecords
group by hasrecords
drop table #header
drop table #detail
[编辑] 注意(响应评论)相关和非相关子查询:
--correlated
select header, case when exists (select 1 from #detail where #detail.header = #header.header) then 1 else 0 end hasrecords from #header
--non-correlated
select #header.header, case when count(#detail.header) > 0 then 1 else 0 end hasrecords from #header left join #detail on #header.header = #detail.header group by #header.header