Postgres SQL - “my_id”必须出现在GROUP BY子句中或用于聚合

时间:2017-06-01 19:50:42

标签: sql postgresql

我有以下sql:

select my_id, count(*) as total_count 
from (select col1, col2 from tableA
      union
      select col1, col2 from tableB
) as BothTable 
order by my_id

并收到此错误column "BothTable.my_id" must appear in the GROUP BY clause or be used in an aggregate function

我如何解决此问题。

1 个答案:

答案 0 :(得分:0)

COUNT(*)会将所有行汇总在一起,因此您无法获得my_id

如果GROUP BY my_id,结果表将为每个my_id分配1行,并计算具有相同值的唯一行数。

my_id, COUNT(*)
<?>, 20

VS

my_id, COUNT(*)
1, 1
2, 10
3, 3
4, 1
5, 5

如果您真的只想要总计数SELECT count(*)而不是SELECT my_id, count(*)