0

我想不通:我有一个名为 ImportaRecords 的表,其中包含市场、zip5、MHI、MHV、TheTable 等字段,我想按 zip5 对所有具有 TheTable = 'mg' 的记录进行分组......我试过这个:

select a.Market,a.zip5,count(a.zip5),a.MHI,a.MHV,a.TheTable from 
    (select * from ImportantaRecords where TheTable = 'mg') a
    group by a.Zip5

但它给了我一个没有聚合函数的经典错误

然后我尝试了这个:

select Market,zip5,count(zip5),MHI,MHV,TheTable from ImportantaRecords where TheTable = 'mg'
    group by Zip5

和同样的事情......</p>

有什么帮助吗?

4

1 回答 1

1

您没有说明您正在使用什么数据库,但如果您收到关于列不在聚合函数中的错误,那么您可能需要将不在聚合函数中的列添加到GROUP BY

select Market,
  zip5,
  count(zip5),
  MHI,
  MHV,
  TheTable 
from ImportantaRecords 
where TheTable = 'mg'
group by Market, Zip5, MHI, MHV, TheTable;

如果按附加列分组会改变您期望的结果,那么您可以使用子查询来获取结果:

select i1.Market,
  i1.zip5,
  i2.Total,
  i1.MHI,
  i1.MHV,
  i1.TheTable 
from ImportantaRecords i1
inner join
(
  select zip5, count(*) Total
  from ImportantaRecords
  where TheTable = 'mg'
  group by zip5
) i2
  on i1.zip5 = i2.zip5
where i1.TheTable = 'mg'
于 2013-05-02T15:57:08.027 回答