-1

我使用 PostgreSQLSELECT DISTINCT ON语法执行了一些查询。我想让查询在每个结果行旁边返回总行数。

假设我有一个my_table如下表:

CREATE TABLE my_table(
    id int,
    my_field text,
    id_reference bigint
);

然后我有几个值:

 id | my_field | id_reference 
----+----------+--------------
  1 | a        |            1
  1 | b        |            2
  2 | a        |            3
  2 | c        |            4
  3 | x        |            5

基本上my_table包含一些版本化的数据。这id_reference是对数据库全局版本的引用。对数据库的每次更改都会增加全局版本号,并且更改将始终向表中添加新行(而不是更新/删除值),并且它们将插入新的版本号。

我的目标是执行一个只检索表中最新值以及总行数的查询。

例如,在上述情况下,我想检索以下输出:

| total | id | my_field | id_reference |
+-------+----+----------+--------------+
| 3     | 1  | b        |  2           |
+-------+----+----------+--------------+
| 3     | 2  | c        |  4           |
+-------+----+----------+--------------+
| 3     | 3  | x        |  5           |
+-------+----+----------+--------------+

我的尝试如下:

select distinct on (id)
    count(*) over () as total,
    *
from my_table
order by id, id_reference desc

这将返回几乎正确的输出,除了total是行数my_table而不是结果查询的行数:

 total | id | my_field | id_reference 
-------+----+----------+--------------
     5 |  1 | b        |            2
     5 |  2 | c        |            4
     5 |  3 | x        |            5
(3 rows)

如您所见,它具有5而不是预期的3.

我可以通过使用子查询和count聚合函数来解决这个问题:

with my_values as (
  select distinct on (id)
    *
  from my_table
  order by id, id_reference desc
)
select count(*) over (), * from my_values

这产生了我的预期输出。

我的问题:有没有办法避免使用这个子查询并有类似的东西来count(*) over ()返回我想要的结果?

4

1 回答 1

1

您正在查看my_table3 种方式:

  1. 找到id_reference每个最新的id
  2. 为每个查找my_field最新的id_referenceid
  3. 计算表中不同的ids数

因此,我更喜欢这个解决方案:

select
    c.id_count as total,
    a.id,
    a.my_field,
    b.max_id_reference
from
    my_table a
    join
    (
        select 
            id,
            max(id_reference) as max_id_reference
        from 
            my_table
        group by
            id
    ) b 
    on
        a.id = b.id and
        a.id_reference = b.max_id_reference
    join
    (
        select
            count(distinct id) as id_count
        from
            my_table
    ) c
    on true;

这有点长(尤其是我编写 SQL 的长而细的方式),但它清楚地说明了正在发生的事情。如果您在几个月后回到它(通常有人这样做),那么您将花费更少的时间来了解正在发生的事情。

最后的“on true”是一个经过深思熟虑的笛卡尔积,因为子查询“c”只能有一个结果,而您确实想要一个笛卡尔积。

子查询不一定有错。

于 2018-01-09T14:18:36.010 回答