【问题标题】:How to calculate a non-inflated count from a denormalized table如何从非规范化表中计算非膨胀计数
【发布时间】:2019-12-27 04:44:40
【问题描述】:

假设我有一个非规范化表,其中包含一个 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_IDs 之前的原始计数结果?

【问题讨论】:

  • 您的第一个表有唯一的 ID?加入的表有唯一的键吗?如果是的话,您可以使用由这些 Id 划分的窗口函数来获取计数..(或带有情况的总和)
  • 这不是典型的M:M 关系吗?如果您不想计算每个apple,那么它应该在查询中。此外,同时拥有表结构和您正在使用的连接可能会有所帮助。

标签: sql postgresql denormalization


【解决方案1】:

您需要在第一个表中使用不同的行标识符 - 可能在其他列中。它可以是一列或多列。然后就可以使用count(distinct)

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

【讨论】:

  • 这完美!第一个表中的唯一行列确实是多列的组合
  • 这对于总和而不是计数如何工作?你不能对 求和
  • @hov 。 . .我建议再问一个问题。
猜你喜欢
  • 1970-01-01
  • 2013-01-18
  • 2011-10-10
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-29
  • 1970-01-01
相关资源
最近更新 更多