postgresql - Postgres : Getting a total related count based on a condition from a related table

标签 postgresql count aggregate

我的 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

purchased_carts 的数字出奇地高,可能与订单项总数乘以购物车数量有关?或许?我对结果感到很困惑。任何帮助将不胜感激。

最佳答案

这应该有所帮助:

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 谓词是一个半连接。

关于postgresql - Postgres : Getting a total related count based on a condition from a related table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38311124/

相关文章:

excel - 如何计算Excel中不同值的重复次数?

MySQL 获取具有特定属性的项目,按包含的属性数量排序

c++ - CMake 添加库 libpq (postgreSQL) mac c++ clion

sql - postgresql 同时更新两个表

python - Groupby nunique 与 unique 与分类数据

php - 与其他记录一起聚合函数

r - 在数据框中聚合数据

r - 聚合/总结每组多个变量(例如总和、平均值)

sql - 如何获取当前日期 - 使用 Postgresql 的两周日期?

postgresql - 在 PostgreSQL 中使用 View 进行访问控制