【问题标题】:Postgres: Getting a total related count based on a condition from a related tablePostgres:根据相关表中的条件获取总相关计数
【发布时间】:2016-07-11 15:46:39
【问题描述】:

我的 sql-fu 并不强大,我确信我在尝试使其正常工作时遗漏了一些简单的东西。我有一组相当标准的表格:

users
-----
id
name


carts
-----
id
user_id
purchased_at


line_items
----------
id
cart_id
product_id


products
--------
id
permalink

如果该用户购买了特定产品,我想获取每个用户购买的购物车的总数。也就是说:如果他们购买的购物车中至少有一个具有特定永久链接的产品,我想要计算购买的购物车的总数,无论其内容如何。

购买的购物车的定义是当 carts.purchased_at 不为空时。

select
  u.id,
  count(c2.*) as purchased_carts

from users u

inner join carts c on u.id = c.user_id
inner join line_items li on c.id = li.cart_id
inner join products p on p.id = li.product_id 
left join carts c2 on u.id = c2.user_id

where 
  c.purchased_at is not NULL 
  and
  c2.purchased_at is not NULL 
  and
  p.permalink = 'product-name'
group by 1
order by 2 desc

purchase_carts 的数字异常高,可能与订单项总数乘以购物车数有关?也许?我对结果感到很困惑。任何帮助将不胜感激。

【问题讨论】:

    标签: postgresql count aggregate


    【解决方案1】:

    这应该会有所帮助:

    select u.id,
           count(*)
    from   users u join
           carts c on c.user_id = u.id
    where  c.purchased_at is not NULL and
           exists (
             select null
             from   carts      c2
             join   line_items l on l.cart_id = c2.id
             join   products   p on p.id      = l.product_id
             where  c2.user_id      = u.id and
                    c2.purchased_at is not NULL 
                    p.permalink     = 'product-name')
    group by u.id
    order by count(*) desc;
    

    exists 谓词是一个半连接。

    【讨论】:

      【解决方案2】:

      bool_or 是你所需要的

      select
          u.id,
          count(distinct c.id) as purchased_carts
      from
          users u
          inner join
          carts c on u.id = c.user_id
          inner join
          line_items li on c.id = li.cart_id
          inner join
          products p on p.id = li.product_id 
      where c.purchased_at is not NULL 
      group by u.id
      having bool_or (p.permalink = 'product-name')
      order by 2 desc
      

      【讨论】:

        猜你喜欢
        • 2020-05-08
        • 2023-03-23
        • 2019-02-06
        • 1970-01-01
        • 2011-01-28
        • 1970-01-01
        • 2019-06-18
        • 2014-01-04
        • 1970-01-01
        相关资源
        最近更新 更多