如何从非规范化表中计算非虚增计数

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

假设我有一个非规范化的表,其中包含一个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表(其中每棵树都有多个苹果)中的联接进一步规范化我的表,它将看起来像这样:

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之前的原始计数结果?

sql postgresql denormalization
1个回答
0
投票
您在第一个表中需要一个不同的行标识符-也许在其他列中。它可以是一列或多列。然后您可以使用count(distinct)

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

© www.soinside.com 2019 - 2024. All rights reserved.