如何从非规范化 table 计算非膨胀计数

How to calculate a non-inflated count from a denormalized table

假设我有一个非规范化的 table,其中包含一个 ID 和一个我需要计算的值。像这样:

 Tree_ID | ...other columns... |  Count_If_True
------------------------------------------------
       1 | ...other values...  |           True
       1 | ...other values...  |           True
       2 | ...other values...  |           True
       2 | ...other values...  |           True
       3 | ...other values...  |           True

在这种情况下,select Tree_ID, count(Count_If_True) from Table group by Tree_ID 将显示:

 Tree_ID |  count(Count_If_True)
---------------------------------
       1 |                     2
       2 |                     2
       3 |                     1

但是,如果我使用来自 Apples table 的连接进一步对 table 进行非规范化(其中每棵树都有多个苹果),它将看起来像这样:

Apple_ID | Tree_ID | ...other columns... |  Count_If_True
------------------------------------------------
       1 |       1 | ...other values...  |           True
       2 |       1 | ...other values...  |           True
       3 |       1 | ...other values...  |           True
       4 |       1 | ...other values...  |           True
       5 |       1 | ...other values...  |           True
       6 |       1 | ...other values...  |           True
       7 |       2 | ...other values...  |           True
       8 |       2 | ...other values...  |           True
       9 |       2 | ...other values...  |           True
      10 |       2 | ...other values...  |           True
      11 |       2 | ...other values...  |           True
      12 |       2 | ...other values...  |           True
      13 |       2 | ...other values...  |           True
      14 |       2 | ...other values...  |           True
      15 |       3 | ...other values...  |           True
      16 |       3 | ...other values...  |           True
      17 |       3 | ...other values...  |           True
      18 |       3 | ...other values...  |           True
      19 |       3 | ...other values...  |           True

这会使我们的 count 膨胀到:

 Tree_ID |  count(Count_If_True)
---------------------------------
       1 |                     6
       2 |                     8
       3 |                     5

是否有一种简单的方法(例如,没有 CTE)来编写单个查询以返回 Apple_ID 引入之前的原始计数结果?

您需要在第一个 table 中有一个不同的行标识符——也许在其他列中。它可以是一列或多列。然后你可以使用 count(distinct):

select tree_id,
       count(distinct <unique row column>) filter (where count_if_true)
from t
group by tree_id;