简体   繁体   English

每个顾客在餐厅消费的总金额是多少? 无法看到不同的 customer_id .. 仅显示所有金额的一个相同 id

[英]What is the total amount each customer spent at the restaurant? Not able to see different customer_id.. shows only one same id for all amounts

Query询问

select customer_id ,(numbers*price) as amount 
from (select *,  count(s.product_id) as numbers
      from sales s group by product_id) as sub1 
inner join
( select s.product_id, price 
  from menu m inner join sales s on m.product_id = s.product_id 
  group by product_id) as sub2 on sub1.product_id = sub2.product_id; 

sample data:样本数据:

INSERT INTO sales ("customer_id", "order_date", "product_id") 
VALUES ('A', '2021-01-01', '1'),('A', '2021-01-01', '2'),('A', '2021-01-07', '2'),('A', '2021-01-10', '3'),('A', '2021-01-11', '3'),('A', '2021-01-11', '3'),('B', '2021-01-01', '2'),('B', '2021-01-02', '2'),('B', '2021-01-04', '1'),('B', '2021-01-11', '1'),('B', '2021-01-16', '3'),('B', '2021-02-01', '3'),('C', '2021-01-01', '3'),('C', '2021-01-01', '3'),('C', '2021-01-07', '3'); 

INSERT INTO menu ("product_id", "product_name", "price") 
VALUES ('1', 'sushi', '10'),('2', 'curry', '15'),('3', 'ramen', '12'); 

Output Output

customer_id   amount
A              30
A              60
A              96

whereas i want it to show A,B,C as customer ids as the amount is calculated correctly for them.而我希望它显示 A,B,C 作为客户 ID,因为金额是为他们正确计算的。 Its showing A as customer_id for all three as first three ids in sales table are for customer A. I tried group by with customer id as well.. it shows only one result, ie A and 30.它将 A 显示为所有三个的 customer_id,因为销售表中的前三个 id 是针对客户 A 的。我也尝试使用客户 ID 进行分组。它只显示一个结果,即 A 和 30。

截屏

seems like you want sales report per product:似乎您想要每个产品的销售报告:

select  product_name, sum(price) amount
from sales s
join menu m on s.product_id = m.product_id
group by product_name
order by sum(price)
product_name产品名称 amount数量
sushi寿司 30 30
curry咖喱 60 60
ramen拉面 96 96

but if you want total sale per customer:但如果您想要每位客户的总销售额:

select  customer_id , sum(price) amount
from sales s
join menu m on s.product_id = m.product_id
group by customer_id
order by customer_id
customer_id客户ID amount数量
A一个 76 76
B 74 74
C C 36 36

db<>fiddle here db<> 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM