【问题标题】:Postgresql selecting specific set of records based on a field valuePostgresql 根据字段值选择特定的记录集
【发布时间】:2017-06-14 00:03:49
【问题描述】:

我有如下所示的 postgresql 数据集,其中 app_id 可能有多个记录。我需要为 bool_flag 为 true 的每个 app_id 选择所有记录,如果 app_id 没有 bool_flag 值等于 true 的记录,则为该应用选择所有值为 false 的记录。

这里是可用数据集的链接 data-set

这是我正在寻找的所需输出,在此先感谢。 desired output

【问题讨论】:

  • 这是一个我们可以帮助您进行编程的社区,但这不是我们为您编写代码的地方。请查看本指南以编写一个好的 SO 问题:codeblog.jonskeet.uk/2012/11/24/…

标签: sql postgresql


【解决方案1】:

这是一种方法:

select t.*
from t
where t.bool_flag
union all
select t.*
from t
where not t.bool_flag and
      not exists (select 1
                  from t t2
                  where t2.app_id = t.app_id and t2.bool_flag
                 );

正如描述所述,它首先获取具有“true”的所有行。然后它获取没有相应“真”行的“假”行。

【讨论】:

  • 感谢@Gordon,我尝试了您建议的解决方案,可能是由于我的知识有限,它没有奏效。无论如何感谢您的回复。使用计数窗口功能(第一条评论)我得到了我想要的东西。
  • @ZindaHu 。 . .你有错误吗?这怎么行不通?
【解决方案2】:

使用count 窗口函数的一种方法。

select app_id,created_date,bool_flag
from (select t.*
      ,count(case when not bool_flag then 1 end) over(partition by app_id) as false_cnt
      ,count(*) over(partition by app_id) as total
      from tbl t
     ) t
where bool_flag or total=false_cnt 

bool_or 的另一种方式。

select t1.* 
from (select app_id,bool_or(bool_flag) as bool_res
      from tbl
      group by app_id
     ) t
join tbl t1 on t.app_id=t1.app_id 
where t.bool_res=t1.bool_flag

【讨论】:

  • 感谢@vkp,您的第一个方法按预期工作。我得到了我想要的结果。谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多