选择 PostgreSQL 中包含行数的表名

问题描述 投票:0回答:1

我使用PostgreSQL 13。我有几张桌子。我想发出一个选择请求,获取这些表的名称以及带有 NULL

updated_date
列的行数。

我可以输出带有 NULL 日期的行数。我这样做:

select count(*)
from TABLE_1
where updated_date is null
UNION
select count(*)
from TABLE_2
where updated_date is null;

-------
 count |
-------
     1 |
     2 |
-------  

我可以这样获取表的名称:

select t.tableoid::regclass as table_name
from TABLE_1 t
where updated_date is null;

------------
 table_name |
------------
    TABLE_1 |
------------

select t.tableoid::regclass as table_name
from TABLE_2 t
where updated_date is null;

------------
 table_name |
------------
    TABLE_2 |
    TABLE_2 |
------------

最后,我需要一个 SQL 请求,它将给我一个结果:

--------------------
 table_name | count |
--------------------
    TABLE_1 |     1 |
    TABLE_2 |     2 |
--------------------

我尝试这样做:

select t1.tableoid::regclass, count(*)
from TABLE_1 t1
where updated_date is null
UNION
select t2.tableoid::regclass, count(*)
from TABLE_2 t2
where updated_date is null;

但我得到了错误:

[42803] ERROR: column "t1.tableoid" must appear in the GROUP BY clause or be used in an aggregate function 

我该如何解决这个问题?

postgresql union
1个回答
0
投票

似乎你需要类似的东西:

select t1.tableoid::regclass t_name, count(*) t_count
from TABLE_1 t1
where t1.updated_date is null
group by t_name
union 
select t2.tableoid::regclass t_name, count(*) t_count
from TABLE_2 t2
where t2.updated_date is null
group by t_name;
© www.soinside.com 2019 - 2024. All rights reserved.