我无法弄清楚: 我有一个名为ImportantaRecords的表,其中包括market,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
但它给了我一个经典的错误,没有一个aggrefate函数
然后我尝试了这个:
select Market,zip5,count(zip5),MHI,MHV,TheTable from ImportantaRecords where TheTable = 'mg'
group by Zip5
和同样的事情......
任何帮助?
答案 0 :(得分:1)
您没有说明您正在使用的数据库,但是如果您收到的错误是关于不在聚合函数中的列,那么您可能需要将不在聚合函数中的列添加到GROUP BY
:< / p>
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'