sql - 选择联合计数和组,多个表,postgresql

标签 sql postgresql

您好,有 12 个表,我想为所有表中的某些字段获取唯一值。 通过运行以下查询(我在 2 个表之间进行了测试),我得到了一个可接受的结果,但是如果两个表中都存储了唯一值,则会重复计数:

SELECT "mmsi", "type", "l", "w", "flag", COUNT (*) FROM test_1 GROUP BY "mmsi", "type", "l", "w", "flag"
UNION
SELECT "mmsi", "type", "l", "w", "flag", COUNT (*) FROM test_2 GROUP BY "mmsi", "type", "l", "w", "flag"

我该如何解决?谢谢

最佳答案

通过聚合每个表,您会得到如下结果:

mmsi   type   l   w   flag   count(*)
123    456    A   B   C      12
123    456    A   B   C      25
234    567    X   Y   Z      17
234    567    X   Y   Z      11

because UNION doesn't detect any duplicates, because of the different count. And if there where two rows with the same count, one would be removed and the count accordingly too small by 50%.

You probably want this:

mmsi   type   l   w   flag   count(*)
123    456    A   B   C      37
234    567    X   Y   Z      28

instead with the total count, no matter in which tables. So get a set of all records first (with UNION ALL), then aggregate.

SELECT mmsi, type, l, w, flag, COUNT (*)
FROM
(
  SELECT mmsi, type, l, w, flag FROM test_1 
  UNION ALL
  SELECT mmsi, type, l, w, flag FROM test_2
) all_records
GROUP BY mmsi, type, l, w, flag

关于sql - 选择联合计数和组,多个表,postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51595565/

相关文章:

mysql - 选择在另一个表中没有特定值的项目

mysql - 为什么在 INNER JOIN 中使用 MAX() 时只能选择两列?

sql - MySQL 查找每个用户的帖子总数

sql - 检查父行是否有任何子行的简单 SQL

ruby-on-rails - 如何仅在记录不存在时才创建记录,避免重复并且不引发任何错误?

mysql - 如何从特殊记录中查找最后记录的计数

mysql - 如何将尽可能多的值插入到另一个表中,因为它是在其他表的特定列中定义的

python - 当 BEGIN 在自动提交模式下的连接上运行时,Postgres 会做什么?

PostgreSQL:如何获取每个单词的首字母并在其后添加句号[.]?

postgresql - 更改表错误添加 2 列