子查询和组合查询

时间:2019-04-25 23:36:43

标签: postgresql

我一直在研究一个问题。我将其分解为以下几个步骤。我很难将所有查询组合在一起以解决以下问题:

  

查找在以下部门中花费超过1000美元的会员   带来了超过10000美元的会员ID订单。

模式:

departments(id, name)
products (id, name, price)
members(id, name, number, email, city, street_name, street_address)
sales(id, department_id, product_id, member_id, transaction_date

步骤1) 我发现部门的收入已经超过10,000美元

select s.department_id
from sales s join products p on 
  s.product_id = p.id 
group by s.department_id
having sum(price) > '10000'

第2步)我找到了他们在其中购物的成员和部门

select *
from members m
     join sales s
     on m.id = s.member_id 
     join departments d 
     on d.id = s.department_id 

步骤3)我将1和2结合起来,找到了拥有10,000多个部门的会员店

select *
from members m
     join sales s
     on m.id = s.member_id 
     join departments d 
     on d.id = s.department_id
where s.department_id in 
    (select s.department_id
    from sales s join products p on 
    s.product_id = p.id 
    group by s.department_id
    having sum(price) > '10000')

第4步)我找到了成员及其ID,电子邮件,total_spending> 1,000 $

select m.id, m.name, m.email, sum(price) as total_spending
from members m join sales s on 
  m.id = s.member_id 
  join products p on 
  p.id = s.product_id 
group by m.id 
having sum(price) > '1000'

步骤5) 所有步骤都是单独工作的,但是当我尝试将它们组合在一起时:

select m.id, m.name, m.email, sum(price) as total_spending
from members m join sales s on 
  m.id = s.member_id 
  join products p on 
  p.id = s.product_id 
where m.id in (select distinct m.id
from members m
     join sales s
     on m.id = s.member_id 
     join departments d 
     on d.id = s.department_id
where s.department_id in 
    (select s.department_id
    from sales s join products p on 
    s.product_id = p.id 
    group by s.department_id
    having sum(price) > '10000'))
group by m.id
having sum(price) > '1000'

输出错误。 (这是在CodeWars上的)如果有人可以指出正确的方向,那真是太好了!谢谢。

1 个答案:

答案 0 :(得分:0)

尝试按member_iddepartment_id分组:

select s.member_id,s.department_id,sum(p.price) as total_spending
from members m
join sales s on m.id = s.member_id
join products p on p.id = s.product_id
where s.department_id in (
        select s.department_id
        from sales s
        join products p on s.product_id = p.id
        group by s.department_id
        having sum(p.price) > 10000 -- the departments which brought in more than $10000 total
    )
group by s.member_id,s.department_id
having sum(p.price) > 1000 -- who have spent over $1000 in one department

如果需要,您可以计算每个成员的花费:

select member_id,sum(total_spending) total
from
  (
    -- the first query is here
  ) q
group by member_id