【问题标题】:List values per quantity and product type列出每个数量和产品类型的值
【发布时间】:2020-11-17 16:06:14
【问题描述】:

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

结果:

client_id   age
1           10-15

客户表:

client_id   age
1   10-15
2   15-20

产品表:

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

【问题讨论】:

    标签: sql postgresql inner-join aggregate-functions having-clause


    【解决方案1】:

    这是你要找的吗?

    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;
    

    【讨论】:

      【解决方案2】:

      使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-01
        • 2021-06-17
        • 1970-01-01
        • 2010-11-24
        • 1970-01-01
        • 2022-12-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多