假设我有一个非规范化的表,其中包含一个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
之前的原始计数结果?
count(distinct)
:select tree_id,
count(distinct <unique row column>) filter (where count_if_true)
from t
group by tree_id;