【发布时间】: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