SQLCASE语句中如何查询多个case

How to query many cases in SQL CASE statement

我正在尝试解决 SQL 在线挑战

我有三个表:

其中一个问题是:每个会员在成为会员之前总共花费了多少物品和金额?

我想我对以下查询的回答是正确的:

with cte as
(
  SELECT 
    CASE WHEN s.customer_id = 'A' THEN count(s.product_id)*m.price END AS purchases_A,
    CASE WHEN s.customer_id = 'B' THEN count(s.product_id)*m.price END AS purchases_B,
    CASE WHEN s.customer_id = 'C' THEN count(s.product_id)*m.price END AS purchases_C,
    case when s.customer_id = 'A' THEN count(s.product_id) END AS total_A,
    case when s.customer_id = 'B' THEN count(s.product_id) END AS total_B,
    case when s.customer_id = 'C' THEN count(s.product_id) END AS total_C
  from sales s
  join menu m on s.product_id = m.product_id
  join members mb on mb.customer_id = s.customer_id and mb.join_date > s.order_date
  group by s.customer_id, m.price
)
select 
  sum(purchases_A) as total_spendings_a,
  sum (total_A) as total_items_A,
  sum(purchases_B) as total_spendings_b,
  sum (total_B) as total_items_B,
  sum(purchases_C) as total_spendings_c,
  sum (total_C) as total_items_C
from cte;

我的问题是。有没有更好的方法或更有效的方法来编写此查询?感觉太长而且重复了。 在这种情况下,我只有三个客户:A、B 和 C 如果我有 100 或 1000 个客户怎么办?

非常感谢

简单地连接表并按成员聚合:

select
  m.member_id,
  coalesce(count(*), 0) as total_amount,
  coalesce(sum(price), 0) as total_price
from members m
left join sales s on s.customer_id = m.customer_id and s.order_date < m.join_date
left join menu p on p.product_id = s.product_id
group by m.member_id
order by by m.member_id;

你提到了 members.member_idmembers.customer_id,所以我都用了。如果这是您请求中的拼写错误,那么只需在我的查询中将错误的列名称更改为正确的列名称即可。