【问题标题】:postgresql select count but not limited to the where clausepostgresql 选择计数但不限于 where 子句
【发布时间】:2022-01-08 01:07:48
【问题描述】:

我似乎无法理解这个 1,也许在 1 个查询中是不可能的。 这就是我所拥有的,但我想要看到的是所有 purchase_orders,shipment_status 在 5 到 25 之间。以及所有 purchase_orders 的计数(电子邮件)。 目前我认为这仅适用于 2 个查询,但我真的希望它可以在 1 个查询中实现。

select name, email, count(email) as cnt_email
from purchase_orders
where shipment_status>5 AND shipment_status<25
group by email, name
having count(email) > 1
order by name

编辑 1:一些背景信息。我们不要求人们向我们注册才能向我们出售产品。所有数据都在 purchase_orders 表中。我们通过他们的电子邮件地址来识别不同的用户,但如果某人是退货卖家并使用不同的电子邮件地址,那将是非常好的。

编辑 2:如果我要写查询,我会写:

select name, email from purchase_orders where shipment_status> 5 and shipment_status<25


select count(email) as cnt_email from purchase_orders having count(email) > 1

我希望这能说清楚。

感谢您的帮助!

【问题讨论】:

    标签: sql postgresql select count where-clause


    【解决方案1】:

    如果我了解您的问题,您可以使用count(*) filter (where ...) 格式来解决您的问题。

    select 
      name, 
      email, 
      count(email) as cnt_email,
      count(email) filter (where shipment_status>5 AND shipment_status<25) as cnt_email_condition
    from purchase_orders
    group by email, name
    having count(email) > 1
    order by name
    

    【讨论】:

    • 谢谢,但我认为这不是我正在寻找的答案。我尝试在我的第二个编辑部分中明确它。很抱歉,如果它令人困惑。
    【解决方案2】:

    我做了我想要的查询。我不会重写以使其适合我在问题中使用的示例。抱歉懒惰。

    select
        po.id, po.name, po.email,
        case
            when po.last_total_price/po.last_total_quantity > 400 then 'Gemiddeld hoge prijs'
            when po.last_total_quantity - count(distinct pol.product_id) > 0 then 'Meerdere exemplaren'
            when (select count(email) from purchase_orders where email=po.email group by email) > 10 then 'Terugkerende verkoper'
        end as afwijking
    from
        purchase_orders po
    left join
        purchase_order_lines pol on pol.purchase_order_id=po.id
    where
        po.shipment_status between 5 AND 25
    group by
        po.id
    order by
        po.name
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多