【问题标题】:Postgresql get count of items based on the conditionPostgresql 根据条件获取项目数
【发布时间】:2020-10-07 18:20:43
【问题描述】:

我有一张这样的桌子

水果 - 状态
-------------------
苹果 - 新
苹果 - 好的
苹果 - 好的
苹果 - 坏
香蕉 - 新
香蕉 - 好的
香蕉 - 坏
橙色 - 新
橙色 - 好的
橙色 - 好的
橙色 - 好的
橙色 - 好的
橙色 - 好的

我想获取未处于“坏”状态的项目以及“正常”的次数。像这样:

水果-okcount
----------------------
橙色 - 5

此时苹果和香蕉处于“坏”状态。 和橘子五次都可以(不包括新状态)。

我试过这个,但它不起作用,因为它也给了苹果和香蕉的“好的”状态。

select * from (select fruit, count(fruit) AS okaycount
from fruits
where  state='okay'
group by fruit) as din
order by din.okaycount desc
limit 10;

也试过这个。没用。

SELECT distinct ndt.fruit, COUNT( ndt.fruit ) as okaycount
FROM(select * from fruits where fruit in (select distinct correlationid 
from fruits
where wcsstatus!='bad')) as ndt
GROUP BY ndt.fruit
HAVING count(*) > 3;

【问题讨论】:

  • “此时”是什么意思? SQL 表表示无序集。
  • 我的意思是苹果和香蕉不需要采摘。但我使用的查询也是拿起苹果和香蕉。

标签: sql postgresql count postgresql-9.4 having-clause


【解决方案1】:

在 Postgres 中,我会在 having 子句中使用过滤计数和布尔聚合来表达这一点:

select fruit, count(*) filter(where status = 'okay') cnt
from fruits
group by fruit
having not bool_or(status = 'bad')

【讨论】:

    【解决方案2】:

    根据你想要的结果,你可以使用:

    select fruit, sum( (status = 'okay')::int )
    from fruit
    group by fruit
    having sum( (status = 'bad')::int ) = 0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      相关资源
      最近更新 更多