union と group by の併用

PostgreSQLで union + group by を使った時のメモ。

普通に使うとできなかった・・・・。
order by が上手くいかない・・・。

結論として、一度 union でデータを引っぱってテーブル化し、それを group by する。

まずは必要なデータを普通に union する。
select id, points from m_point_log union all select id, points from point_log;

unionしたデータを tb_uni として from で指定して、group by する。
select tb_uni.id, sum(tb_uni.points) as uni_point from (select id, points from m_point_log union all select id, points from point_log) as tb_uni group by tb_uni.id order by uni_point desc limit 10;

勉強になりました。