如何获取在所有时期都有非空值的行,但在同一公司的其他文档中不存在?

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

我有一个数据库,其中有不同的组件,有'当前''历史'时期的值。这些组件可以属于同一公司的不同文档。"期间 "是一个布尔值列,包含-'当前'& '历史'。

我的派生表在多次连接后是这样的------。

company_id       document_id       component_id      value      period
1000                   100             1              456      current
1000                   100             1              870      historical
1000                   100             2              67       current 
1000                   100             2              NULL     historical
1000                   200             2              67       historical

我想从上面获取component_id'1':document_id'100'的所有期间都有非空值,但document_id'200'不存在。document_id","company_id"& "component_id "列的值不知道,所以不能用于查询。

sql postgresql
1个回答
0
投票

如果我的理解是正确的,你想要的组件有一个文档,而不是所有时期的值。 如果是这样的话。

select distinct component_id
from t
group by component_id, document_id
having count(value) over (filter where period = 'current') = 0 or
       count(value) over (filter where period = 'historical') = 0 ;

如果这是你想要的,那么这就是少数几种情况之一。select distinct 是可以与 group by.


0
投票

我知道你想要的组件,对于一个特定的公司,只属于一个公司。document_id 而没有 null 值。

如果是这样,您可以通过 component_idcompany_id的过滤逻辑,并在 having 条款。

select company_id, component_id
from mytable t
group by company_id, component_id
having 
    bool_and(value is not null)              -- no "value" is "null"
    and min(document_id) = max(document_id)  -- only one distinct "document_id"
© www.soinside.com 2019 - 2024. All rights reserved.