列出每个数量和产品类型的值

List values per quantity and product type

我正在努力完成一项很可能很容易的任务。我想根据客户订购的产品列出客户的年龄 - 4 个香蕉和 3 个苹果。结果应显示已购买至少 4 个香蕉和 3 个苹果的客户的年龄列。菠萝不应该被考虑在内。

结果:

client_id   age
1           10-15

客户table:

client_id   age
1   10-15
2   15-20

产品table:

product_id  client_id   product_name
1   1   banana
2   1   banana
3   1   banana
4   1   banana
5   1   apple
6   1   apple
7   1   apple
8   1   pineapple
9   2   apple
10  2   apple
11  2   banana
12  2   pineapple

使用group byhaving:

select c.client_id, c.age
from clients c
inner join products p on p.product_id = c.client_id
where p.product_name in ('banana', 'apple')
group by c.client_id
having count(*) filter (where p.product_name = 'banana') >= 4
   and count(*) filter (where p.product_name = 'apple' ) >= 3

这是您要找的吗?

select c.*
from products p join
     clients c
     using (client_id)
group by c.client_id
having count(*) filter (where product_name = 'banana') >= 4 and
       count(*) filter (where product_name = 'applies') >= 3;