我想得到大於男女平均年齡的人
原表:
在gauss200下執行以下語句:
SELECT stname,age,gender,AVG(age) FROM att_test01 GROUP BY gender HAVING age > AVG(age);
報錯:column att_test01.stname must appear in the group by clause or be used in an aggregate function
gauss200是基於開源的postgres-XC開發的分布式關系型數據庫系統,這是postgres常見的聚合問題。
解決方法如下:
SELECT b.stname,b.gender,b.age,a.avg FROM (SELECT gender,AVG(age) AS avg FROM att_test01 GROUP BY gender) a LEFT JOIN att_test01 b ON a.gender = b.gender AND b.age > a.avg;
將聚合放到子查詢當中,然后與原表進行聯合查詢。
執行結果: